Category Archives for CakePHP

Scaffolding in Cakephp

About Scaffolding in CakePhp . Application scaffolding is a technique that allows a developer to define and create a basic application that can create, retrieve, update and delete objects. Scaffolding in CakePHP also allows developers to define how objects are related to each other, and to create and break those links.

All that’s needed to create a scaffold is a model and its controller. Once you set the $scaffold variable in the controller, you’re up and running.

CakePHP’s scaffolding is pretty cool. It allows you to get a basic CRUD application up and going in minutes. So cool that you’ll want to use it in production apps. Now, we think its cool too, but please realize that scaffolding is… well… just scaffolding. It’s a loose structure you throw up real quick during the beginning of a project in order to get started. It isn’t meant to be completely flexible, it’s meant as a temporary way to get up and going. If you find yourself really wanting to customize your logic and your views, its time to pull your scaffolding down in order to write some code. CakePHP’s Bake console, covered in the next section, is a great next step: it generates all the code that would produce the same result as the most current scaffold.

Scaffolding is a great way of getting the early parts of developing a web application started. Early database schemas are subject to change, which is perfectly normal in the early part of the design process. This has a downside: a web developer hates creating forms that never will see real use. To reduce the strain on the developer, scaffolding has been included in CakePHP. Scaffolding analyzes your database tables and creates standard lists with add, delete and edit buttons, standard forms for editing and standard views for inspecting a single item in the database.

To add scaffolding to your application, in the controller, add the $scaffold variable:

class CategoriesController extends AppController {

var $scaffold;

}

for more info : http://manual.cakephp.org/view/105/Scaffolding

Cakephp - Data validation

In this article we are explain Data validation’s  importance , as it helps to make sure that the data in a Model conforms to the business rules of the application. For example, you might want to make sure that passwords are at least six characters long, or ensure that usernames are unique. Defining validation rules makes form handling much, much easier. There are many different aspects to the validation process.

What we’ll cover in this section is the model side of things. Essentially: what happens when you call the save () method of your model. For more information about how to handle the displaying of validation errors, check out the section covering FormHelper.

The first step to data validation is creating the validation rules in the Model. To do that, use the Model::validate array in the Model definition, for example:

<?php
class User extends AppModel {
var
$name = ‘User’;
var $validate = array();
}
?>

From the example above, the $validate array is added to the User Model, but the array contains no validation rules. Assuming that the users table has login, password, email and born fields, the example below shows some simple validation rules that apply to those fields:

<?php
class User extends AppModel {
var $name = ‘User’;
var $validate = array(
‘login’ => ‘alphaNumeric’,
‘email’ => ‘email’,
‘born’ => ‘date’
);
}
?>
This last example shows how validation rules can be added to model fields. For the login field, only letters and numbers will be accepted, the email should be valid, and born should be a valid date. Defining validation rules enables CakePHP’s automagic showing of error messages in forms if the data submitted does not follow the defined rules.

CakePHP has many validation rules and using them can be quite easy. Some of the built-in rules allow you to verify the formatting of emails, URLs, and credit card numbers.

To know more about validation : http://manual.cakephp.org/view/125/data-validation

CakePHP development Tips

1) Creating static pages in easy steps

If you need to create several pages that didn’t use any models and contained static data inside the default layout. You must first create a controller for these pages and define an action for each static page you needed. However, this solution seemed tedious and would make it difficult to quickly add new pages. Enter the pages controller - simply create a view inside the views/pages/ folder and it’ll automatically be rendered in /pages. For example, if you created /views/pages/blognol.thtml it would be accessible via http://www.example.com/pages/blognol
Note: Instead of .thtml in cakephp 1.2 we will use .ctp

2) Adjusting the page title – in static pages

If you’re using the pages controller and you need to change the page title, add the following to your view:
<? $this->pageTitle = ‘Blognol Title.’; ?>
3) Adjusting other data sent to the layout in static pages

If you need to send data to the layout (such as a variable indicating what section to highlight on the navigation bar), add this to your view:

<? $this->_viewVars['somedata'] = array(’some’,'data’); ?>
That array should then be accessible as $somedata inside your layout.

4) How to create a simple admin center

If you need to create an administrative back-end for your CakePHP site and would like all the actions with administrative capabilities to exist under a specific folder, open up config/core.php and uncomment:
define(’CAKE_ADMIN’, ‘admin’);

This will then make all actions that are prefixed with “admin_” to be accessible via:
/admin/yourcontroller/youraction. For instance, if I created an action in my posts controller called “admin_add,” I would access this via: www.example.com/admin/posts/add
From there I could simply password the admin folder to prohibit unwanted users from adding posts.
5) Viewing the SQL queries that are running behind the scenes
It is very easy to see the SQL queries that CakePHP is running by adjusting the DEBUG constant in config/core.php. 0 is production, 1 is development, 2 is full debug with SQL, and 3 is full debug with SQL and dump of the current object. I typically have debug set at 2, which renders a table at the bottom of the page that contains SQL debug information.

If rendering a table at the bottom of your site is constantly breaking your layout during development (especially if you’re making AJAX calls and you’re getting SQL inside your pages, not just the bottom), you can easily style this table to be hidden by adding this to your CSS:

#cakeSqlLog { display: none; }

This will allow you to view debug information in the HTML source code without your layout getting mangled, just don’t forget to set debug back to 0 when your site goes live.
6) Using bake.php
Bake is a command line PHP script that will automagically generate a model, controller, and views based on the design of your database. I highly recommend using scaffolding to get a prototype going of a table that may change a lot in the beginning. If you’re fairly certain the data is not subject to any drastic change, I recommend using bake instead. With bake all the files are generated and written to disk and you can make modifications from there. It saves a lot of time doing the repetitive tasks such as creating associations, views, and the basic CRUD controller operations.

Using bake is really easy. Once you have a table(s) in your database created, change directories to the /cake/scripts/ folder and run:
php bake.php

If you choose to bake interactively it’ll walk you through the steps required to create your model, controller, and views. Once everything has been baked I usually go through all the generated code and make custom modifications as needed.

7) Check the permissions when moving cake around

When I changed from the development server to the live server I tarred up my entire cake directory and scp’d it to the new server. Immediately I started having an issue where any time the debug level was set to 0 (production mode), data would not be returned for certain database calls. This was a bit of a catch 22 since I needed to view debug information to troubleshoot the problem.
Someone in #cakephp kindly pointed out that permissions on the /app/tmp folder need to be writeable by apache. I changed the permissions to 777 and the issue went away.

8) Complex model validation

I needed to validate beyond just checking to make sure a field wasn’t empty or it matched a regular expression. In particular, I needed a way to verify that the email address users registered with was unique. In the manual.cakephp.org I found this gem, which covers some advanced methods of validation that were very useful.
Note : For cakephp 1.2 http://manual.cakephp.org/view/125/data-validation

9) Logging errors

$this->log(’Something broke’);
This will log your error to /tmp/logs/ (I initially made the mistake of thinking it would log it to the apache error log)

10) Creating a controller that uses other models

Suppose you have a controller that needs data from a bunch of different models, simply add this to the top of your controller:

class yourController extends AppController
{
var $uses = array(’Post’,'User’);
}

This controller would then have access to both the Post and the User model.

11) Creating a model for a table that doesn’t actually exist in the database

If you need to create a model and controller without actually having an associated table in the database, you particularly wanted to make use of the $validate array so you could easily validate my fields and keep the validation logic in the model. CakePHP will throw an error if you create a model for a table that doesn’t exist. Adding this to the model fixed the problem:
var $useTable = false;

You can use this to change tables names as well.
var $useTable = ’some_table’;

12) Call exit() after redirecting

This should be no surprise to anyone who has done any serious web development in the past, but make sure you call exit() after running $this->redirect() if there’s code afterward that you don’t want to run. I’ve always done this in the past, but I made the assumption that $this->redirect() would make an exit call for me (which it didn’t).

13) Inserting multiple rows in succession

If you had a situation where you needed to iterate through a list of items and insert new rows for each. You quickly discovered that if you insert an item and then immediately insert another, the item that is inserted next doesn’t insert at all. Instead the previously inserted row was being updated. For example:

$items = array(’Item 1′,’Item 2′,’Item 3′);
foreach ($items as $item) {
$this->Post->save(array(’Post’ => array(’title’ => $item)));
}

This code will result in a single entry in the posts table: “item 3.” CakePHP inserted “item 1″, but then updates it to become “item 2,” then “item 3″ because $this->Post->id gets the value of the last inserted ID. Normally this functionality is very useful, but in this particular instance it was not. I found was to setting $this->Post->id = false after each insert solved the problem.

Update: Someone emailed me and apparently the proper way of doing this is to call create() to initialize the model and then set/save your new data.

14) Writing your own SQL for HABTM relationships

I had an issue with trying to create a HABTM (has-and-belongs-to-many) relationship where I needed to specify my own SQL statement. According to the docs (at the time of this writing) you should set finderSql in your model, but according to the cakePHP source you should set finderQuery instead. It’s just a foul-up in the docs, but I figured it’d be worth noting to save others from having to figure it out for themselves. Trac ticket here: https://trac.cakephp.org/ticket/1217

15) Customizing HTML generated by the Helper

I needed to change the default <option> generated when I called $html->selectTag() to say something like “Please Select” rather than an empty space (default). I also wanted radio buttons to have labels so the user doesn’t have to click exactly on the radio button itself but can instead click anywhere on the text associated with it.

Create the file /app/config/tags.ini.php and add the following:
; Tag template for a input type=’radio’ tag.
radio = “<input type=”radio” name=”data[%s][%s]” id=”%s” %s /><label for=”%3$s”>%s</label>”

; Tag template for an empty select option tag.
selectempty = “<option value=”" %s>– Please Select –</option>”

You can get a full list of available tags in /cake/config/tags.ini.php. I wouldn’t recommend modifying that file, however, because you could lose your changes when you upgrade CakePHP.

16) Creating a custom 404 error page

If you need to change the page that users see when a document is not found, create:
/app/views/errors/error404.thtml

CakePhp a PHP Framework

CakePHP is a rapid development framework for PHP that provides an extensible architecture for developing, maintaining, and deploying applications. Using commonly known design patterns like MVC and ORM within the convention over configuration paradigm, CakePHP reduces development costs and helps developers write less code.

Features of CakePHP

  • No Configuration - Set-up the database and let the magic begin
  • Extremely Simple - Just look at the name…It’s Cake
  • Active, Friendly Community - Join us #cakephp on IRC. We’d love to help you get started.
  • Flexible License - Distributed under the MIT License
  • Clean IP - Every line of code was written by the CakePHP development team
  • Best Practices - covering security, authentication, and session handling, among the many other features.
  • OO - Whether you are a seasoned object-oriented programmer or a beginner, you’ll feel comfortable

You can cake tutorial from : http://book.cakephp.org/view/219/the-cakephp-blog-tutorial