PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 9, 2022

[FIXED] CakePHP 3 - Reusing Controller Logic

 January 09, 2022     cakephp-3.0, controller, dry     No comments   

Issue

I have been wondering about this before, I'll take my current application as an example.

In this application we have Users, Apps and a much of other models. All these models are modified normally, with add, edit and delete actions. The point is the controller logic behind this is basically identical for each model. However, the model name is of course different everywhere.

Question: what is a proper way of reusing the standard controller actions for different models?

I know AppController code is shared, so that would be a place to start. But then I can't figure out how to do the model selection properly.

An example of the core code of an edit page would be:

$entity = $model->get($id);
$model->patchEntity($entity, $this->request->getData());
if ($model->save($entity))
    //...
else
    //...

$this->set(compact('entity'));

Solution

If you are following the CakePHP's naming conventions then follow this

In your AppController:-

$modelName = $this->name;    //This will give you the model name
$model = $this->$modelName;  //Instance of the  model object
$model->find('all');

EDIT:-

Let us consider you have two controller

  1. ProductsController
    2.CategoriesController -->//Both extends the AppController

And your add() is same for both the controller,
Then in your both ProductsController and CategoriesController

public function add(){
  parent::add();        //this will call to the add() of AppController
}

Then in you AppController

public function add(){
   $modelName = $this->name;    //This will give you the model name
   $modelObject = $this->$modelName;
   $entity = $this->$modelObject->newEntity($this->request->data, ['validate' => false]);
   $this->$modelObject->save($entity);
}


Answered By - bikash.bilz
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing