Using Inflector singularize and camelize for taking out model name in CakePHP

We can use CakePHP library’s Inflector::singularize() and Inflector::camelize() methods for taking out corresponding model name from a controller name (provided we follow CakePHP’s naming conventions well).

Let’s take an example to see it in practice.

We already know that we can call an existing controller action from another controller using requestAction. Also we can place an action at a common place like app_controller to be used by multiple controllers (child classes). Let’s place a “add” action in our app_controller to add records from two different controllers i.e. “users” controller and “recipes” controller, but, first take a look how they look at their actual places.

First one is users controller having add action within:

class UsersController extends AppController {
	function add()	{
		if($this->User->save($this->data))	{
			$this->Session->setFlash(__('User added successfully!'));
			$this->redirect('index');
		}	else	{
			$this->Session->setFlash(__('User could not be added.'));
		}
	}
}

and here is recipes controller’s add action:

class RecipesController extends AppController {
	function add()	{
		if($this->Recipe>save($this->data))	{
			$this->Session->setFlash(__('Recipe added successfully!'));
			$this->redirect('index');
		}	else	{
			$this->Session->setFlash(__('Recipe could not be added.'));
		}
	}
}

Both work well at their corresponding places and i don’t have any complain whatsoever. But, as being a lazy person i want just one common action in place of two which could perform the “add” task for me. So what i do, i just cut users controller’s “add” action and paste it inside AppController class and make some minor changes to perform the same task without any problem (i comment out recipes controller’s add action as well so i could use the same action from recipes controller as well). Here i go:

class AppController extends Controller {
	function add()	{
		$model = Inflector::camelize(Inflector::singularize($this->params['controller']));
		if($this->$model->save($this->data))	{
			$this->Session->setFlash(__($model.' added successfully!'));
			$this->redirect('index');
		}	else	{
			$this->Session->setFlash(__($model.' could not be added.'));
		}
	}
}

Literally , it’s not a very good approach to have single “add” action for multiple controllers. I use it here merely for demonstration purpose so that you could get an idea how to use Inflector effectively to get model name and hence this example post. Scrap me if how do you like the idea.

3 thoughts on “Using Inflector singularize and camelize for taking out model name in CakePHP

  1. That works, if you only ever plan on adding a model from a controller’s default model.

    Better would be to loop over the Controller::uses array and compare the models there to keys in Controller::data and save them as it finds matches.

Leave a Reply

Your email address will not be published.