Archive | CakePhp RSS feed for this section

cakePhp authentication example continued

5 Jan

In previous post I discuss the basic and general usage of cakephp authentication. In this post I am going to code and explain how to write a simple sign up application. This article will not only cover authentication but also models, forms and view etc.

So lets get started.

First of all create a table named “user”  by executing the following sql query.

CREATE TABLE 'user' (

'id' int(11) NOT NULL auto_increment,

‘username’ varchar(30) NOT NULL,

‘password’ varchar(30) NOT NULL,

’email’ varchar(255) NOT NULL,

‘created’ datetime NOT NULL,

‘modified’ datetime NOT NULL,

PRIMARY KEY (‘id’)

)

Now create a model in app/models with name user.php and write following code in that model.

 

<?
 

class User extends AppModel

{

var $name=’User’;

var $useTable=’user’;

var $validate=array(

‘username’ => array(

‘notempty’ => array(

‘rule’ => array(‘minLength’,1),

‘required’ => true,

‘allowEmpty’ => false,

‘message’ => ‘Enter Username’

),

‘checkUnique’ => array(

‘rule’ => array(‘checkUnique’,’username’),

‘message’ => ‘Name already taken. Choose another.’

)

),

‘password’=>array(

‘notempty’ => array(

‘rule’ => array(‘minLength’,1),

‘required’ => true,

‘allowEmpty’ => false,

‘message’ => ‘Enter Password’

),

‘passwordsimilar’=>array(

‘rule’ => ‘checkPasswords’,

‘message’ => ‘Passwords must match.’

)

),

’email’ => array(

‘rule’ => ’email’,

‘required’ => true,

‘allowEmpty’ => false,

‘message’ => ‘Enter valid email’

),

);

function checkUnique($data,$fieldName){

$valid = false;

if(isset($fieldName)&&($this->hasField($fieldName))){

$valid = $this->isUnique(array($fieldName=>$data));

}

return $valid;

}

function checkPasswords($data) {

if($data[‘password’] == $this->data[‘User’][‘password2hashed’])

return true;

return false;

}

}

Explanation:

First we extend our model form cakePhp AppModel class. By doing so, we inherit all the method of that class.

Next we define name of the model and the table (database table) used by this model class. We then define our validate array that is crucial for validating submitting data against the database table. This will insure that the data will not be inserted until and unless valid.

You can put as many table fields as you want and cake will do the rest for you.

You can clearly see in this array that we are defining validation rules for some of the table fields. The first one is the username. We will not insert data in the database until user enter a valid and unique name. if user enter empty username through form. He will be notified with error message. Similarly if he enter a name which already exist in the table another error message will be display saying that “username already taken choose another one”. Although cake provide us validation rules for “allowEmpty” and “required” to ensure that user don’t left fields empty, however to check uniqueness we will need to define our own rule. The lines

 

'checkUnique' => array(

‘rule’ => array(‘checkUnique’,’username’),

‘message’ => ‘Name already taken. Choose another.’

)

in our validate array call our custom defined method

function checkUnique($data,$fieldName){
                        }

$valid = false;

if(isset($fieldName)&&($this->hasField($fieldName))){

$valid = $this->isUnique(array($fieldName=>$data));

                        return $valid;

            }

in this function we check if the $fieldName is passed and is in the User table. If yes then we check its uniqueness by calling a mehod isUnique() provided by cakePhp and passing it the field data. If the name is not already taken, isUnique() method will return true, false otherwise. And at the end of the function we return this value.

 

Next we define validation rules for password field. Make sure that it is not empty and matched to the “confirm password”. Here again we define our own function for ensuring that both password match. The function

 

function checkPasswords($data) {

if($data[‘password’] == $this->data[‘User’][‘password2hashed’])

return true;

return false;
}

check that both password match. If not it will return false, data will not be inserted in the database table and user will be notified with “password must match” error.

Next we define validation rule for email field and make sure that user enter a valid email address.

That’s it we have now defined our own model and will go forward to create our controller and call this model on appropriate action.

So lets define our own controller.

In app/controllers create users_controller.php and write following code

 

<?php
 

class UsersController extends AppController {

var $name = ‘Users’;

var $uses=array(‘User’);

var $components = array(‘Auth’);

function beforeFilter(){

$this->Auth->allow(‘signup’);

}

function signup(){

if (!empty($this->data)) {

if(isset($this->data[‘User’][‘password2’]))

$this->data[‘User’][‘password2hashed’] =$this->Auth->password($this->data[‘User’][‘password2’]);

$this->User->create();

if ($this->User->save($this->data)) {

$this->Session->setFlash(‘Congratulations! You have signed up!’);

$this->redirect(array(‘controller’ => ‘questions’,’action’=>’home’));

} else {

$this->Session->setFlash(‘There was an error signing up. Please, try again.’);

$this->data = null;

}

      }

}

}

Explanation:

We first extend our controller form AppController, define its name, model and components its uses.

Next we define beforFilter() method and allow singup action to be executed whether or not user is authentic.

The action “signup” is important. We are putting most of our code in this action.

First we check if the form is posted by checking the data as $this->data. If it is not empty we then check that the passowrd2 is set. If it is true then we create hashed password with the statement

$this-> Auth->password($this->data[‘User’][‘password2’]);

and assign it to the $this->data[‘User’][‘password2hashed’];

this is important to save hashed password.

Next we call $this->User->create() to load the model and prepare it for the next action.

We then call save action of the model as

$this->User->save($this->data) by passing it the data posted. This function return true if data is successfully inserted in the database table.

If it return true we set flash message and redirect to the home page of the question controller otherwise we set error message to flash helper and set posted data to null.

 

We have now defined our model and controller, now its time to write our view code.

Create views/users/signup.ctp and write the following code in it.

 

<?php if($form->isFieldError('User.username')) e($form->error('User.username', null, array('class' => 'message'))); ?>
 

<?php if($form->isFieldError(‘User.password’)) e($form->error(‘User.password’, null, array(‘class’ => ‘message’))); ?>

<?php if($form->isFieldError(‘User.email’)) e($form->error(‘User.email’, null, array(‘class’ => ‘message’))); ?>

<h2>Sign Up</h2>

<?php e($form->create(‘User’, array(‘action’ => ‘signup’)));?>

<fieldset>

<label for=”UserUsername” class=”usernamelabel”><span>

Your Name</span></label>

<?php e($form->text(‘username’, array(‘class’=> ‘fullwidth’))); ?>

<label for=”UserEmail” class=”emaillabel”><span>Your Email

</span></label>

<?php e($form->text(’email’, array(‘class’=> ‘fullwidth’))); ?>

<label for=”UserPassword” class=”passwordlabel”><span>

Password</span></label>

<?php e($form->password(‘password’, array(‘class’=> ‘fullwidth’))); ?>

<label for=”UserPasswordRepeat” class=”passwordrepeatlabel”>

<span>Re Password</span></label>

<?php e($form->password(‘password2’, array(‘class’=> ‘fullwidth’))); ?>

<?php e($form->submit(‘Sign Up’, array(‘div’ => false,

‘class’ => ‘submitbutton’))); ?>

</fieldset>

<?php e($form->end()); ?>

The code seem a bit complex, however it is very simple if you break it.

In the first three line we check for the error in case of submitting un valid form. If any of the error occur we display it.

 Next we create our our form and set its action.

 

That’s it we have now create a simple sign up application. If you point to

http://localhost/cake/users/signup/

you will see a simple sign up form. You can fill it and it will do everything for you.

Any question feel free to ask.

Advertisements

CakePhp authentication example

4 Jan

One nice thing in cakePhp is that it has written nearly all the code for you. You will need to write very little code while developing your application.

Example is its scaffold functionality. I’ll cover it later on.

Another very good example is Authentication.

If you want that specific controller’s actions should only be executed after user authentication, you will need to just write a single line of code in that controller. Consider you have a controller like

<?php

class PostsController extends AppController

{

var $name = "Posts";

function view(){

}

}
And you want that only authentic user can access its view action, write

class PostsController extends AppController

{

var $name = "Posts";

var $components=array('Auth');

function view(){

}

}
 

That’s it. You can clearly see that we have only added single line of code var $component = array(‘Auth’). It tell cakePhp to allow access to any of the “postsController” action when user is authentic.

 Now if you are not authentic and write

http://localhost/cake/posts/view

it will redirect you to User’s controller=>login action.

Before accessing any of the action of the posts controller you will need to be an authentic user.

However may not want this functionality in all controllers. Web application always contains pages that can be accessed by anybody. To achieve this functionality you will need to add another function to your controller. E.g

 

class PostsController extends AppController

{

var $name = "Posts";

var $components=array('Auth');

function beforFilter(){

$this->Auth->allow('view');

}

function view(){

}

}
 we added single function beforeFilter() and single line of code $this->Auth->allow(‘view’);

beforeFilter() is an important function called cakePhp controller callback. I’ve discuss this in my previous post. It is called and executed before action executing any action within controller in which it is defined. So when you write

http://localhost/cake/posts/view

cakePhp will first call beforeFilter() and execute it and then call “view” action.

In this function we have told cakePhp that allow access to the “view” action. In this case user will be granted access regardless of authentication.

Defining your own components in cakePhp

1 Jan

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');

CakePhp callbacks

1 Jan

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.

CakePhp controller with example

1 Jan

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.

CakePhp Routing

1 Jan

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]'

)

);

CakePhp Installation and configuration

17 Dec

Installation of cake is very simple.

Download cake from cakephp.org and place it into your root directory. After placing it in the root directory. Simply write in your browser

http://localhost/cake/

you will be served with the default page, saying that “change config/database.php.default to config/database.php”. To do this open root_dir/cake/app/config/ and rename database.php.default to database.php.

keep in mind that the database.php.default is in the “app/” directory.

Now if you refresh the page you will see a message “Your database configuration file is present”. However you will see some warnings. To remove these warning you will need to make changes to your app/config/database.php file.

Open the file and make following changes.

var $default = array(

‘driver’ => ‘mysql’,

‘persistent’ => false,

‘host’ => ‘localhost’,

‘login’ => ‘root’,

‘password’ => ”,

‘database’ => ‘database_name’,

‘prefix’ => ”,

);

All the above information should match to your mysql configuration information, especially host, login, password, and database name.

Now after making these changes and saving the file. Refresh your url. You will see a message

“Cake is able to connect to the database”.

That’s it you have now installed and configured your cakephp successfully.