10 Useful things to know about cakephp

Incase you don’t know cakephp is a rapid development framework for php which uses the Model View Controller pattern and is essentially the php equivalent of ruby on rails. I first jumped into cake when i realised i needed to move on from the way i was building websites. I desperately needed a new way of working and i narrowed down my choices to either cakephp or zend and i decided on cakephp. Its a great framework and i have no regrets, it has made my life alot easier and i feel i could tackle any other framework with ease now. However at first it was a bit of a strugle there was so much to learn and i took the plunge by using it straight in my next website project which took me alot longer than it should have. Anyway with the knowlege i have now i thought i’d share some simple tips that may make your cake experience easier. 1. Stopping controllers from telling me its missing a layout. Quite often i’ll put a function for an ajax callback in my controller or i might be quickly trying to test something by dropping it in a new function, usually i will not have created a view for this as there my not be any need for it.

Configure::write('debug', 2);
$this->autoRender = false;

2. Models without tables You may have the need for a model which doesn’t actually have a table, for example i use a contact model for validating my contact form on a site. To be able to do this open up your model file and set the usetable.

class Contact extends AppModel {
    	var $name = 'contact';
    	var $useTable = false;
    	var $_schema = array(
            'name'		=>	array('type'=>'string', 'length'=>100),
            'email'		=>	array('type'=>'string', 'length'=>255),
            'details'	=>	array('type'=>'text')
    	var $validate = array(
    		'name' => array(
    			'rule'=>array('minLength', 1),
    			'message'=>'Name is required' ),
    		'email' => array(
    			'message'=>'Must be a valid email address' ),
    		'details' => array(
    			'rule'=>array('minLength', 1),
    			'message'=>'Feedback is required' )

3. However tempting it may be try to stick to the rules cake has laid out. Quite often when first using cake i would just do whatever i can to make things work the way i want. I have since learned from this that it is far better to stick to working the way cake wants you to. For example using controllers models and views for their purpose not mixing them together with other areas. To avoid problems use the bake feature of cake. Its quite simple, create your database structure as you want it then go to your command prompt and type cake bake app This will create your entire site and take you through the steps to configure everything. 4. Check for behaviours, plugins and addons available before trying to do it all yourself. Want to be able to use titles and text for you urls or want to add comments easily or upload files then look for behaviours created by other users of cake they will save you alot of time and as you learn more you can begin to develop your own making each project reusable. One of my favourite behaviours is sluggable, id recommend it if you want to add a slug to a table. Its so easy to setup too add the required database fields then in your model tell it how to act and the rest is done by magic!

var $actsAs = array('Sluggable' => array('separator' => '_', 'overwrite' => true));

5. Do i have to use these damn helpers? Being able to write html and php the way you want is important and knowing how to still be dynamic is equally important heres how to output an image or link without using the helpers.

<img src="<?php echo $this->webroot; ?>img/coolimage.jpg" alt="cool image" />
<a title="link to cool gallery" href="<?php echo $this->webroot; ?>galleries/view/12">Click here</a>

6. Creating a controller that uses other models There are a few methods of doing this you can add the models to your uses array but i’d recommend against that, try to keep your uses array clean and with what the original controller is for. Instead consider redirecting the user to the controller that actually deals with that specific thing. For example clicking delete on an image in a gallery instead of the gallery controller deleting the image have it redirect to a image controller a url like image/delete/2 and once its deleted redirect back to where it came from using the referrer. Instead of this

class NewsController extends AppController
var $uses = array('News','User');

Use something like this chaining the associated models

class NewsController extends AppController
    	var $uses = array('News');
    	function index()

Or if they have no relationship try importing and using it

//import the model
$Category = new Category();
$data = $Category->find('all',array('conditions'=>array('Category.parent_id IS NULL')));

7. Regular Static Pages You can create any page you like by creating a file in /app/views/pages for example create about.ctp then in your webbrowser where your cake app is running add /pages/about on the end and you will see this page. This is great for adding simple pages but what about when you need some php in there? I’d suggest creating a controller view but no model for a new page then, not only will this link to /app/about instead of /app/pages/about but it will mean you can throw in some php in a controller or use a model if you need to at the last minute. 8. Complex pagination queries A few times the way the regular cakephp pagination works has limited what i need, to work around this i have either written my own in the models file or in that controller added the joins and relationships i need to get the data i want. Heres an example of a habtm relationship between some products and categories.

//ids is data of chosen categories
$ids = array(1,2,3,4);
$this->paginate = array('Product' => array('limit' => 60,'joins' => array(
    			'table' => 'products_categories',
    			'alias' => 'ProductsCategories',
    			'type' => 'inner',
    			'conditions'=> array(
    				'ProductsCategories.product_id = Product.id'
    			'table' => 'categories',
    			'alias' => 'Category',
    			'type' => 'inner',
    			'conditions'=> array(
    				'Category.id = ProductsCategories.category_id' ,
    				'Category.parent_id' => $ids
$data = $this->paginate();
$this->set('products', $data);

9. Make the most of elements If you haven’t already heard of elements i suggest you have a read online. If there is anything in your website that is used multiple times in different areas you can create an element for it. Similar to a simple php include file an element can be used to great effect. For example a search box or the top 5 news articles sidebar or anything that you want to recreate multiple times that doesn’t have to be in the main layout.ctp file. Cake elements can also be used to show error messages and more, heres a basic element. Element file view

    	$jobs = $this->requestAction('/jobs/latest');
## Latest Vacancies
foreach($jobs as $job)
    	echo "
      * ";
    	echo $html->link($job['Job']['name'],"/vacancies/view/".$job['Job']['slug']);
    	echo "

Controller the request action calls for the data

$Job->find('all', array('order' => 'Job.created DESC', 'limit' => 10));

Where ever you want this element to appear just call it like so

$this->element('latestvacancies'); ?>;

10. How to use jquery as cakephp ajax If you prefer using jquery then you will want to setup cakephp to use it by default and heres how. In your app controller make sure you have Js as Jquery like below

class AppController extends Controller {
    	var $helpers = array('Html','Javascript','Form', 'Session', 'Js' => array('Jquery'));

Then you are going to need to have jquery.js in your webroot/js folder then add the following to your of your layout file default.ctp

echo $this->Html->script('jquery.min')."\n"; // Include jQuery library

and at the very bottom of the same file you will want to add the buffer like so.

echo $this->Js->writeBuffer(array('onDomReady'=>true));

Onces thats done you should be able to use the js helper using jquery easily, heres an example of creating a link which loads content into a div called #maincontent and fades it in and out or shows an error if it doesn’t work.

echo $js->link("View types","/types",array(
    		'update' => '#maincontent',
    		'before' => $this->Js->get('#maincontent')->effect('fadeOut', array('buffer' => false)),
    		'complete' => $this->Js->get('#maincontent')->effect('fadeIn', array('buffer' => false)),
    		'error' => $js->alert('There was an error loading this page, please try again')

Well i hope some of these tips and snippets have helped. If not then try checking out the cakephp google groups at groups.google.com/group/cake-php or readup on how everything works in the cakephp book book.cakephp.org.


  • avatar-rana
    # Rana
    Nice Post Very Helpfull For me

Comments are currently closed