MVC (Laravel) where to add logic

后端 未结 4 924
感情败类
感情败类 2020-11-27 09:04

Let\'s say whenever I do a CRUD operation or modify a relationship in a specific way I also want to do something else. E.g., whenever someone publishes a post I also want to

4条回答
  •  失恋的感觉
    2020-11-27 09:29

    What I use to do to create the logic between controllers and models is to create a service layer. Basically, this is my flow for any action within my app:

    1. Controller get user's requested action and sent parameters and delegates everything to a service class.
    2. Service class do all the logic related to the operation: input validation, event logging, database operations, etc...
    3. Model holds information of fields, data transformation, and definitions of attributes validations.

    This is how I do it:

    This the method of a controller to create something:

    public function processCreateCongregation()
    {
        // Get input data.
        $congregation                 = new Congregation;
        $congregation->name           = Input::get('name');
        $congregation->address        = Input::get('address');
        $congregation->pm_day_of_week = Input::get('pm_day_of_week');
        $pmHours                      = Input::get('pm_datetime_hours');
        $pmMinutes                    = Input::get('pm_datetime_minutes');
        $congregation->pm_datetime    = Carbon::createFromTime($pmHours, $pmMinutes, 0);
    
        // Delegates actual operation to service.
        try
        {
            CongregationService::createCongregation($congregation);
            $this->success(trans('messages.congregationCreated'));
            return Redirect::route('congregations.list');
        }
        catch (ValidationException $e)
        {
            // Catch validation errors thrown by service operation.
            return Redirect::route('congregations.create')
                ->withInput(Input::all())
                ->withErrors($e->getValidator());
        }
        catch (Exception $e)
        {
            // Catch any unexpected exception.
            return $this->unexpected($e);
        }
    }
    

    This is the service class that does the logic related to the operation:

    public static function createCongregation(Congregation $congregation)
    {
        // Log the operation.
        Log::info('Create congregation.', compact('congregation'));
    
        // Validate data.
        $validator = $congregation->getValidator();
    
        if ($validator->fails())
        {
            throw new ValidationException($validator);
        }
    
        // Save to the database.
        $congregation->created_by = Auth::user()->id;
        $congregation->updated_by = Auth::user()->id;
    
        $congregation->save();
    }
    

    And this is my model:

    class Congregation extends Eloquent
    {
        protected $table = 'congregations';
    
        public function getValidator()
        {
            $data = array(
                'name' => $this->name,
                'address' => $this->address,
                'pm_day_of_week' => $this->pm_day_of_week,
                'pm_datetime' => $this->pm_datetime,
            );
    
            $rules = array(
                'name' => ['required', 'unique:congregations'],
                'address' => ['required'],
                'pm_day_of_week' => ['required', 'integer', 'between:0,6'],
                'pm_datetime' => ['required', 'regex:/([01]?[0-9]|2[0-3]):[0-5]?[0-9]:[0-5][0-9]/'],
            );
    
            return Validator::make($data, $rules);
        }
    
        public function getDates()
        {
            return array_merge_recursive(parent::getDates(), array(
                'pm_datetime',
                'cbs_datetime',
            ));
        }
    }
    

    For more information about this way I use to organize my code for a Laravel app: https://github.com/rmariuzzo/Pitimi

提交回复
热议问题