Zend Framework

Archive for January 1st, 2009

Defining your own components in cakePhp

Posted by Faheem Abbas on January 1, 2009

Although cake is shipped with some standard components like Email, security, sessions and authentication etc, however it is like piece of cake to define your own components in cakePhp

If certain code is used again and again in your application, it is better to define your own component and put that code in it. The code written in component can be reused wherever you want in your application.

In your “/app/controllers/components/” directory create a file say math.php and put the following code in it.

<?

class MathComponent extends Object

{

function sum($x,$y){

return $x+$y;

}

}

the code above is very simple to understand. To define a component you will need to extend it form Object class. And then define your own function.

Later in your controller, you can call this method as

<?php

class IndexController extends AppController

{

$components = array('Math');

function index()

{

$x = 5;

$y = 5 ;

$sum = $this->Math->sum($x,$y);

}

}

in the first line $component = array(‘Math’); we tell the controller that we will use Math component in our action. And then in line $sum = $this->Math->sum($x,$y), we call the method we have already defined in our component.

If you want to access specific component within another, you can write

<?php

class MyComponent extends Object

{

var $components = array('Math');

function doStuff()

{

$result = $this->Math->sum(5,5);

}

}

If you want to access specific model in your component, simply write

$user = ClassRegistry::init('User');

here ‘User’ is the name of the model we want to use in our component and then

$totalUsers = $user->find('count');

Posted in CakePhp | 2 Comments »

CakePhp callbacks

Posted by Faheem Abbas on January 1, 2009

Before going to discuss how to create components, models and other stuff in cakePhp I would like to tell you about some important functions called callback, that can be defined in your controller classes and these can play a very vital role in some situations.

  1. beforeFilter : This function, if defined in your controller class, is called before any action is called.

If you have worked in Zend framework and have heard about or used pre and post dispatch hooks, you may have better idea of this. Zend provides preDispatch() function which is called before any action is called. So this beforeFilter is similar to Zend framework preDispatch() method.

This function can be very helpful for the functionality like checking and activating session before action is called or more importantly to check user(s) role(s) before any controller action is called. The most simple example would be

<?php

class AuthController extends AppController

{

function beforeFilter()

{

// put code which you want to be executed before each action

}

function index()

{

// action logic here

}

}

so whenever you call

localhost/cake/auth/index, function beforeFilter() will be called and the code in it will be executed before the code in the index() action.

2.beforeRender():

This function as its name indicate, is called after the action logic but before rendering the view template code. This function is rarely used.

3. afterFilter() : this function is like postDispatch() hook of the Zend framework. It is called after everything, i.e action and view template code, is executed.

Posted in CakePhp | Leave a Comment »

CakePhp controller with example

Posted by Faheem Abbas on January 1, 2009

As I have already defined core configuration and routing in my previous post, its now time to wit my hands with cakePhp controllers.

In MVC archecticture controllers are used to integrate models and views.

It is not a hard job to define a controller in cakePhp. You would need to define a class exetending it from AppController class of cakePph. E.g

<?php

class MyController extends AppContrller

{

}

write the code above and save it in you app/controllers directory. That’s it you have now define your first controller in cakePhp.

You can define as many action in this controller class as you want. Simple write

<?php

class MyController extends AppContrller

{

// this is view action.

function view()

{

}

}

In the code above you can see that we have defined our view action.

If you want to call this action from you browser, simply write

http://localhost/cake/my/view

I assumed that you have installed your cake in “cake” directory.

Next thing you may want to use might be model(s). If you want to use specific models in the controller, write

class MyController extends AppContrller

{

// initializing models array

var $uses=array('Company','User');

// this is view action.

function view()

{

}

}

The statement var $uses = array(‘company’,'user’) tells that we want to use these two models in our controller.

Models play a extremely vital role in MVC archeticture and we hopefully will cover this topic in our later posts.

Another very nice feature cakePhp provide is that you can define your own components in addition to those shipped with cakePhp itself called cakePhp standard components, and can use them in your application.

Components are very useful in case you need similar functionality throughout you application. Just put those function in your component and simply use that component in your controller as

$components = array('Component_name'); e.g

$components =array('Email');

Email is standard component shipped with cakePhp.

You can define as many component in this array and can use them in your controller. Components will need to be define in separate post, I think. So I am leaving this discussion here.

Next important thing that you can include in your controller and get benefits out of it, would definitely be helpers. Simply write

$helper = array('helper_name');

in your controller. This way you can include and use as many helpers as you want.

Before ending my post, I would better discuss the parameter that can be accessed in controller.

The most important data that you want to get in your controller would definitely be the one submitted through form, either using get or post method.

This is very simple. Write

$data = $this->data;

this will give you entire data submitted. You can have individual fields as

$first_name = $this->data['User']['first_name'];

I assumed that you have field name ‘first_name’ in your form while ‘User’ is the name of the form.

Another very handy attribute would be

$posted_data = $this->params;

This not only return the data submitted via form, but also additional data like controller name, action name, plugin etc.

If you want to get specific data like controller name, write

$controller_name = $this->params['controller'];


and similarly

$action_name = $this->params['action'];


If you want to get query string, write

$query_string = $this->params['pass'];

and url can be get as

$url = $this->params['url'];

this will return an array of url and query string.

At the end I would like to discuss a very important method cake provide us in the controller is set(). This method is used as assign() method of the zend framework.

If you want to assign something like variable or array of variables to the view template, simply write

$this->set('color','blue');

this variable then can be accessed in view template as

$color = $color;

You can also write

$this->set(array('color'=>'blue','font'=>'arial'));

While assigning variable to the view template.

Two other important method are

redirect() and flash();

redirect can be used as

$this->redirect(array('controller'=>'orders','view'=>'thanks'));

and flash as

$this->flash ($message, $url, $pause);

Where message is what you want to be displayed, url is very your page should be redirected after the message is displayed and $pause is an integer indicating how long you want your message to be displayed.

Posted in CakePhp | 1 Comment »

CakePhp Routing

Posted by Faheem Abbas on January 1, 2009

Routing specify which Contorller/Action to be called on specific request.

If you successfully install cake and browse

http://localhost/cake/post/view

this will call PostController’s “view” action. If don’t have the specified controller or action cake will route your request to default controller that display missing controller error.

Similarly /cake/post/viewOrders will route your request to PostController’s “view_orders” action and /cake/post/view/5 to PostController’s “view($key)” action.

If you define following controller

<?php

class PostController extends AppController

{

function view($key,$value)

{

}

}

?>

and browse

http://localhost/cake/post/view/age/26. this will call Post controller “view” action. The parameter $key will be mapped to “age” and $value to “26″.

If you want to pass variables to specific action simply write in browser

http://localhost/cake/post/view/name:fahim/address:my address/

Now in your action simply write

<?php

class PostController extends AppController

{

function view()

{

$name = $this->passedArgs['name'];

$address = $this->passedArgs['address'];

}

}

?>

Before wrapping my article, I would like to tell about a very useful file cakePhp provides for defining your routing.

Open “/app/config/route.php” and you will find some routing mechanism already defined.

If you want that request to certain controller should be route some specific pages, you can define your criteria in this file and cake will do the magic for you.

If you want that all request in your application to /blog/view should be route to post/view, simple define

Router::connect(

'blog/view',

array('controller'=>'post','action'=>'view')

);

in this file.

A more complex example would be

Router::connect(

'/:controller/:year/:month/:day',

array('action'=>'index','day'=>null),

array(

'year' => '[12][0-9]{3}',

'month' => '0[1-9]1[012]',

'day' => '0(1-9)[12][0-9]/3[01]'

)

);

Posted in CakePhp | Leave a Comment »