phpcakephpactiverecordabstractioncakephp-2.7

CakePHP: agnostic model manipulation


Is there a way to fetch/manipulate a model agnostically in the AppController in order to avoid DRYness in the controllers of the application ? For example:

//AppController.php
public function find_all()
{
   return $this->AppModel->find('all'); 
   //I know this does not work but to give you the idea
}

And in children controllers of the app:

//FoosController.php
public function some_function()
{
   $data = parent::find_all();
   //List of Foo entities
}

Or:

//BarsController.php
public function some_other_function()
{
   $data = parent::find_all();
   //List of Bar entities
}

Is there a solution CakePHP can provide ? Or using reflection, maybe ?

Thank you for your help !


Solution

  • I figured out a way to achieve what I was looking for:

    //AppController.php
    public function find_all()
    {
       return $this->{$this->modelClass}->find('all'); 
    }
    

    NOTE: If you are performing repetitive CRUD operations without any real business logic or authorization involved (as I currently am), you can also use you these lines of code to persist entites without being aware of the model that is being handled in the AppController.

    //AppController.php
    if (!$this->{$this->modelClass}->save($this->request->data))
    {
       $validationErrors = $this->{$this->modelClass}->validationErrors;
       //error logic here
    }
    else
    {
       //success logic here
    }