HasOne association type

CakePHP 2 Comments »

A powerful feature in Cake is the relational data association provided by the model definition. There are four types of associations:
- hasOne
- hasMany
- belongsTo
- hasAndbelongsToMany

After we define the association between 2 models Cake will automatically fetch the data between the “glued” models. For example if the Car model is related to the Image model and is using a hasOne association type when we will retrieve the data using findAll for example in a controller there will be retrived both Car and Image records: $this->Car->findAll()
To use this types of relations correctly is indicated to use naming conventions like:

- Foreign Keys: singular-model-name_id. For example, a foreign key in the "images" table pointing back to the Car a given Image belongs to would be named "car_id".
- Tables name should be at plural
- Model names should be singular form of the tables names.

Example of association and querying data with hasOne between two models Car model and Image model in this cases:

Location: app/models/car.php

  1. class Car extends AppModel
  2.   {
  3.     var $name = 'Car';
  4.     var $hasOne = array(Image' =>               
  5.        array('className' => 'Image',
  6.        'conditions' => '',
  7.        'order' => '',
  8.        'dependent' => true,
  9.        'foreignKey' => 'car_id'
  10.        )
  11. // the hasOne array is what Cake is using to create the association between this 2 models
  12.     );
  13.   }

When we will retrieve data using find() or findAll() calls upon Car model we should see our associated Image model data as well.

  1. $car = $this->Car->read(null, '20');
  2. print_r($car);
  3.  //will  output:
  4.    (
  5.    [Car] => Array
  6.         (
  7.          [id] => 20
  8.          [name] => Ferrari
  9.          [model] => Testarosa
  10.          [year] => 1977
  11.          [status] => sold
  12.           )
  13.          [Image] => Array
  14.          (
  15.          [id] => 34
  16.          [title] => sqwertmnx312.jpg
  17.          [width] => 200
  18.          [height] = 150
  19.          )
  20.   )


Saving data in CakePHP

CakePHP 2 Comments »

To save in your model using CakePHP you only have to supply that data to a specific model using the save() method.
The data needs to be in the following form:

  1. (
  2.     [ModelName] => Array
  3.         (
  4.             [yourfieldname] => 'value'
  5.             [anotherfieldname] => 'value'
  6.         )
  7. )

To post data in this form to a controller for example is very easy using HTML helpers that are implemented in Cake. Everything we need to care about is that form elements are looking like: data[Modelname][fieldname] .

For example to acces a certain variable in a controller we will use;

  1. $name_var = $this->data[‘Modelname’][‘formvariable’];

The input form in the view will look something like this:

  1. $html->input('Modelname/formvariable')

In a form construction using helpers is best to respect the model structure using to give names to form elements the same names like fields we want to fill in the database.
Using this convention data sent from forms will be formatted automatically and will look putted in $this->data within you controller, so saving data becomes very easy.

Example of saving data:

  1. function add() // action add
  2.     {
  3.         if (!empty($this->data))   // checking to see if $this->data is not empty
  4.         {
  5.             if ($this->Car->save($this->data)) // is data is saved returns true
  6.             {
  7.                 $this->flash('Your post has been saved.','/posts'); //displaying message with link
  8.             }
  9.         }
  10.     }

In the example above we are saving data in the Car model.
If you want to validate your data you can easily do this using your model.

  1. class Car extends AppModel
  2. {
  3.     var $name = Car';
  4.     var $validate = array(
  5.         'name'  => VALID_NOT_EMPTY,
  6.         'model'   => VALID_NOT_EMPTY
  7.         'year'   => VALID_NOT_EMPTY
  8.    );
  9. }

Cake will check variables: name, model and year not to be empty.
In on of the next posts I will describe how easy is to save data in multiple related models.

Retrieving data in CakePHP

CakePHP 7 Comments »

A function to retrieve data in CakePHP is the findAll() model function.
It has the following syntax:

  1. findAll($conditions, $fields, $order, $limit, $page, $recursive);
  2. string $conditions;
  3. array $fields;
  4. string $order;
  5. int $limit;
  6. int $page;
  7. int $recursive;

For example to retrive all the data from a table you will use following:

  1. $this->set($var, $this->Modelname->findAll());

With the “set function” the $var value will be send to the view. In the case above all the fields of the table will be retrieve.

Examples using findAll()

To sort the data by a certain field we can use:

  1. $this->set($var, $this->Modelname->findAll(null, null, ‘Modelname.field’));

For ascending:

  1. $this->set($var, $this->Modelname->findAll(null, null, ‘Modelname.field ASC’));


  1. $this->set($var, $this->Modelname->findAll(null, null, ‘Modelname.field DESC’));

Only first 10 results:

  1. $this->set($var, $this->Modelname->findAll(null, null, ‘Modelname.field DESC’, 10));

The second results page:

  1. $this->set($var, $this->Modelname->findAll(null, null, ‘Modelname.field DESC’, 10, 2));

Putting some conditions in the query:

  1. $this->set($var, $this->Modelname->findAll(‘Modelname.id> 1’, null, ‘Modelname.field DESC’, 10 ));


Elements in CakePHP

CakePHP 1 Comment »

Elements are small blocks of code that can be reused in different pages of a layout.
Elements need to be uploaded in /app/views/elements/ directory and have the .thtml extension.
By default elements haven't acces to any data, if you want to give it access to any data you have to send it as a parameter in an array.

Example without parameters:

  1. <?php echo $this->renderElemet('element_name'); ?>

Example of calling an element with parameters:

  1. <?php echo
  2. $this->renderElement('element_name', array("text" => "Here is text for example."));
  3. ?>

This pieces of code need to be inserted in your view.

Changing the default layout in CakePHP

CakePHP No Comments »

If you want to change the default welcome layout of the CakePHP framework you have to overidde it, you can do this by creating a default.thtml file in the app/views/layouts directory. Once you have done that you have only to specify to Cake to insert the controller view code in to the right place (our default layout in this case). You can to this by including the $content_for_layout and optionally $title_for_layout variables.

You can customize as you want your template by uploading images and styles in the webroot directory app/webroot which becomes your site root from now on.


  1. <head>
  2. <title><?php echo $title_for_layout; ?></title>
  3. <body>
  4. <!--Here some html code -->
  5. <div id="header">
  6. <div id="menu">...</div>
  7. </div>
  8. <?php echo $content_for_layout; ?>
  9. <!-- Here is the rest of the code -->

After this is done you will see that cake changed the default layout with the one of yours and also the content of the page is cake successfully installation text. Now we have to insert in the new layout our own content. A quick way to do this is creating a controller in app/controllers named as we want but according to cake rules it has to be a plural, for example sites_controller.php . Inside of the controller we will have following code:

  1. class SitesController extends AppController {
  2.     var $uses = array();
  3.     function index(){
  4.     // here will be your code;
  5.     }
  6. }

var $uses = array(); I use this because I don’t want Cake engine to look for a model regarding this controller. If you omit this line you will get a “missing model” error.

Browsing the http://example.com/sites/index it should reveal a page having your layout applied but with an error of ”missing view”. To get rid of that error you have to create a file called index.thtml in the app/views/sites/ (you have to create the directory also) file that will be the view for your index action of your Sites controller.
If you want visitors to point directly to a certain action of a controller when they enter your website you can do that using “Route Configuration”. Routing is like a mod_rewrite with the help of which you can map URLs to controllers actions and params and back. Routes are configured in app/config/routes.php .
You can find more information about this at the Chapter Configuration on Cake’s Manual.

In our case our routing rule should look like this:

  1. $Route->connect('/', array('controller' => 'sites', 'action' => 'index'));

‘/’ – represents the URL we want to map, the domain itself in this case;
‘sites’ – is the controller we wish to invoke
‘index’ – the action we wish to invoke

Now when we point on http://example.com/ Cake engine should display the following page http://example.com/sites/index (sites controller with the index action).

Started learning CakePHP

CakePHP No Comments »

I've started again learning CakePHP framework and I decided to write as I learn some practical examples of using this development tool. If you know something about Cake, I invite you to read this following posts. I know they are not with a solid documentation behind but maybe you can use some things from here.

About CakePHP

CakePHP No Comments »

I started some time ago to study a php rapid development framework called CakePHP. I've heard about it from a colleague of mine. He uses and is very comfortable with it. After I study it a little I realized that this is a very powerful tool in a hand of a good programmer, you can develop robust web applications having a lot of flexibility by your hand. It is based on design patterns like Association Data Mapping, Front Controller and MVC.
Unfortunately I didn't get deeper in it being caught with works but it is in high priority in my list.

XHTML 1.o Specifications

Xhtml/CSS No Comments »

For those who are working with the XHTML 1.0 here are the full specification list of this markup language, with the W3C recommendations from January 2000 revised in August 2002. You can find content like :
Normative Definition of XHTML 1.0
Differences with HTML 4
Compatibility Issues
Element Prohibitions
HTML Compatibility Guidelines
and other useful things.

Great resources for CSS

Xhtml/CSS No Comments »

css-discuss.incutio.com it is a great resource for CSS, it is divided in areas like browsers testing, editors of css, css concepts, example of layouts, switching (about rendering mode), hacks, sizing text, sizing images, and a lot more of tricks very useful for a professional web developer.

Theme designed by N.Design Studio
Entries RSS Comments RSS Log in