You are on page 1of 9

CakePHP Cheatsheet v 1.0.

0
Phil Wright
phil@origin3.net
current as of 4/19/2007

In your controller, us this to go back to the previous page:

$this->redirect($this->referer());

====

here are some more tips, if you have built the associations for your models you can access other models like this

$this->CurrentModel->AssocModel->save();

and if you want to do a custom query instead of $this->Model->findBySql() you can also use
$this->Model->Query()

here is some code to for the AppController when using admin_ or for potentially any controller.

function beforeFilter() {
//checks for var User in Session and if page is an admin page and that User is
admin level
if(!$this->Session->check('User') && stristr($this->action, 'admin_') && $this-
>Session->read('User.user_level') !='admin')
$this->redirect('/users/login');
}
===

Never use ‘url’ as a querystring parameter with Cake. Cake uses this.

The folder /app/webroot/files is not passed to cake with mod_rewrite rules. Use this for files (such as java .jar
files, etc..)

Access the controller from a view through $this->controller->doSomething();

GENERATE Dynamic SelectBox:

selectTag ($fieldName, $optionElements, $selected=null, $selectAttr=array(), $optionAttr=null,


$showEmpty=true, $return=false)

Controller

$gallery_options = $this->Gallery->generateList($condition, null, null,'{n}.Gallery.id','{n}.Gallery.title');


$this->set('gallery_options',$gallery_options);

View

echo $html->selectTag("Gallery/title",$gallery_options,0,array('class'=>'gallery_select'),null,false);

Set showEmpty to true for a blank option selected first or false to eliminate the blank option.
I have kept track of things I learned about cake over the past month. I also pooled from sources on the web including:

21 Things I learned about Cake


CakeBaker

Please let me know if you have something to add. Especially Model tricks and tips.

Good Stuff

1. Pass objects from the conrtoller to the view.


Create a class and place the definition in app/vendor/test.class.php

In the controller add vendor(‘test.class’); // make sure above the class definition

Create an instance of the object in your controller.


$my_object = new test();
$this->set(‘my_object’, $my_object);

Then in your view call a method from the function:

$my_object->display_message();

Wow! I just passed an object to my view.

2. Cake Manual and Cakesheet PDF Files


Cake Manual in PDF form
Cakesheet

3. DOCUMENTATION: Multiple sources.


Don't just rely on the manual.

CakePHP Manual
15 Minute Blog Tutorial
CakePHP API Documentation
CakePHP Bakery
Bakery - Pagination
Bakery - FCKeditor Integration
CakePHP Naming Conventions
http://cakeforge.org/
Change the default extension from .thtml
Edit the file /cake/libs/view/view.php

Line: 154

var $ext = ‘.thtml’;

Session: Check to see if Session is set.


$this->Session->check($var);

Model: Accessing association Models


If you have built the associations for your models you can access other models like this

$this->CurrentModel->AssocModel->save();

If you want to do a custom query instead of $this->Model->findBySql() you can also use:

$this->Model->query($sql)

Also, here is some code to for the AppController when using admin_ or for potentially any controller.

function beforeFilter() {

//checks for var User in Session and if page is an admin page and that User is admin level

if(!$this->Session->check('User') && stristr($this->action, 'admin_') &&


$this->Session->read('User.user_level') !='admin'))

$this->redirect('/users/login');
}

APP: Creating a Simple Admin Center


Tp create an administrative back-end for your CakePHP site, open up config/core.php file 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 example, if you created an action in your ‘posts’ controller called "admin_add," you would access this via:
www.example.com/admin/posts/add

From there you can simply password protect the admin folder to prohibit unwanted users from adding posts.

APP: CakePHP folder structure


app/config/database.php – place your database name, user id and password in this file.
app/config/core.php – change the debug options here. The variables / constants are available in your entire app.
app/webroot/js – javascript files
app/webroot/css – css style sheets
app/webroot/img – images

APP: Using BAKE


Bake is a command line PHP script that will ‘automagically’ generate a model, controller, and views based on the design
of your database. If you're fairly certain the table and data structure are not subject to any drastic changes use BAKE to
generate all the files necessary for the app. 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 your table(s) created for your database, do the following:

At a command prompt or shell change directories to the /cake/scripts/ folder and type: 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 go through all the generated code and make custom modifications (as needed).

APP: Permissions for the TMP directory must be 777


When you move your cake application to a new server or location, change the permissions on the /app/tmp folder to 777.

Logging Errors

There is a build in loggin system with Cake. Insert into your code:

$this->log('Something broke');

This will log your error to app/tmp/logs/

App: Webroot is the default path


The functions that redirect or create a link or include a css file or javascript file all have $this->webroot built in. You only
need to specify the path following the webroot.

i.e.

$this->redirect("controller/action"); == /app/webroot/controller/action
echo $html->css(‘myfile’); == /app/webroot/css/myfile.css
echo $javascript->link(‘myjs’); == /app/webroot/js/myjs.js

App: Viewing SQL Queries Processed in the Background


By changing the DEBUG constant in the /app/config/core.php file, you can see the SQL queries that CakePHP is
running in the background.

0: Production mode. No error output, no debug messages shown.


1: Development mode. Warnings and errors shown, along with debug messages.
2: Same as in 1, but with SQL output.
3: Same as in 2, but with full dump of current object (usually the
Controller).

Sometimes the rendering of the debug table at the bottom of your site can break your layout during development. You can
easily style this table to be hidden by adding this to your views css (it normally has no style):
.cakeSqlLog { display: none; }

APP: Go to your view and type this code in:


pr($this);

This will give you a ton of information and variables about your controller/view/model

Here are a few highlights:

$this->webroot == your cake application root

$this->here == the current url and view file name (without the extension)

$this->action == the current view filename (without the extension)

$this->base == base url of the current view

$this->viewPath = the cake app path to the current view i.e.


/app/views/medium/add_media == path of just meiduml

I also highly recommend checking out the $this->params variable (in your CONTROLLER)
pr($this->params);

APP: Custom 404 Error Page


Create a custom error page for your app
/app/views/errors/error404.thtml

APP: You can get a full list of available tags in


/cake/config/tags.ini.php.
Create the file /app/config/tags.ini.php for your own overrided tags.

APP: Call exit() after $this->redirect


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).

App: Always use an array


Even if you use just one helper, component or model use an array and not a string.

var $helpers = array("Pagination");


var $components = array("MyComponent");
var $uses = array(‘MyModel’);

** Note: vendor is actually a global function. Call in by vendor(‘myclass’,’myclass1’, etc)

App: Cake Global Functions


Cake Global Functions and Constants

Highlights:

pr(mixed $data) : convenience function equivalent to echo "<pre>" . print_r($data) .


"</pre>";

e($text ) : convenience wrapper for echo()

low($string) : convenience wrapper for strtolower()

up($string) : convenience wrapper for strtoupper()

r($search,$replace ,$subject ) : convenience wrapper for str_replace()

APP: Creating a select box


In the controller:

var $uses = array("<MODEL NAME>"); // make sure the model you use is loaded

$title_list = $this->Post->generateList(null, null, null,'{n}.Post.id','{n}.Post.title');

In the view:

$my_selected_index = 1; // select the first option


echo $html->selectTag("Post/title", $title_list, $my_selected_index);

App: CORE.PHP
If you want to define a global variable for the whole application you can put it in the /app/config/CORE.PHP file. It is
loaded with all pages.

define(‘MY_GLOBAL_VAR’, ‘testing’); // put in core.php

App: Personal functions and classes


Copy your personal functions and classes in the /app/vendors directory. Then use vendor("ClassName", “MyFunctions’,
etc…) to include them in your controller or view.

** note: You could also put them in your app/app_controller.php (if created) I recommend including only those functions
that are you will use in ALL your controllers, in the app/app_controller.php file and save the rest in the vendor.

VIEWS: Static Pages


Pages that don't use any models and contain static data inside the default layout. Enter the pages controller - simply
create a view inside the views/pages/ folder and it'll automatically be rendered in /pages (i.e. /views/pages/matt.thtml
would be accessible via http://www.example.com/pages/matt)

To change the page title for your static pages in a view:

<?= $this->pageTitle = 'New title of your page.'; ?>


Adjusting other data sent to the layout
If you need to send data to a static page add this to your view:

<?= $this->_viewVars['somedata'] = array('some','data'); ?>

That array will be accessible as $somedata inside your layout.

CONTROLLER: Using other table MODELS in one controller


You can use more than one model within your controller. Let's say you have two models 'modelOne' (for table
modelOnes) and 'modelTwo' (for table modelTwos). In your modeltwos.controller.php you can use both models by:

var $uses = array('modelOne','modelTwo');

$components

Just like $helpers and $uses, this variable is used to load up components you will need:

Var $helpers = array(‘Javascript’, ‘HTML’);


var $components = array('fck',’comp1’,’mail’);

MODEL: Creating a model for a table that doesn't actually exist in the
database
Cake will throw an error if you create a model for a table that doesn't exist. Adding this to the model fixes the problem:

var $useTable = false;

You can use this to change tables names as well.

var $useTable = 'some_table';

MODEL: Advanced Model Functions


I highly recommend reading over the Model Class Reference at least once. Here's a few key functions I wasn't aware of
that I found to be very useful:

generateList()
(Populate select boxes with data from associated tables)

findBySql()
SQL Query

findCount()
Returns number of rows matching given SQL condition

hasAny()
Returns true if a record that meets the given conditions exists.

getLastInsertID()
After you save a record you can get the last id
Controller & Model: Saving model data
When saving a Model, make sure to put the $this->data[‘ModelName’] in the save method
(i.e., $this->EmailSent->save($this->data[‘EmailSent’])

Also, remember that all data form one or more models is saved in $this->data. ie. $this->data[‘EmailSent’][id’] is there
as well as another included model $this->data['EmailReceived][‘id’];

MODEL: Create a new record to save in the model


It’s easy to create a new record in a table without a view. This also helps when adding field data after the user submits a
view.

$new_record = $this->MyModel->create(); // create a new record

$new_record[‘MyModel’][‘create_date’] = date(“m/d/Y”); // add current date


$new_record[‘MyModel’][‘description’] = “This is a test”; // add some text

$this->MyModel->save($new_record); // save my new record

MODEL: Save a bunch of records


foreach ($items as $item) {
$this->Post->save(array('Post' => array('title' => $item)));
}

** this causes only one record to save. Use this instead:

foreach ($items as $item) {


$this->Post->create();
$this->Post->save(array('Post' => array('title' => $item)));
}

Controller: Global app_controller


You can copy the /cake/app_controller to /app/app_controller and customeize as you like!

Controller: Calling a function in a different Controller


Let’s say you have a great function in ControllerA called getUserList() that you want to call in ControllerB.

Use the following syntax in ControllerB

$retval = $this->requestAction('/controllera/getUserList);

You could then pass it along to your view:

$this->set(userListResults', $reval);

Controller: Use a Query String with Cake


Let’s say you want to use this Query String with your Cake controller.
http://localhost/holdstill/add_media?project=2&media_type=3

In your controller, use the $this->params[‘url’] object. In this case it will return (upon Form Submit from your view)

$this->params =>

Array(
[url] => medium/add_media
[project] => 2
[media_type] => 3
)

Make sure to check to see if the variable has been set before using it. I use the code:

$media_type = (empty($this->params['url']['media_type'])) ? 'Not Found' : $this->params['url'][‘media_type'];

You could also use isset. ** Note that you must use “POST” as your form method and not “GET”.

Controller: Customizing your Controllers


Suppose you needed an array of colors to be available to every view rendered by your controller but you don't want to
have to define this data in every action. Using the beforeRender() callback will allow you to do this:

function beforeRender() {
$this->set('colors',array('red','blue','green');
}

This would make $colors accessible in every view rendered by that controller. beforeRender() is called after the controller
logic and just before a view is rendered.

There's also beforeFilter() and afterFilter(), which are called before and after every controller action. For more information,
read up on callbacks in the models section of the manual.

You might also like