CakePHP Hints 1.0: A Refresher

Hey all, as usual I don’t have a whole lot of time to explain myself or go into detail.

I’ve been getting back into cakephp and I’ve forgotten so much shit that I’m finding it useful to log all of this stuff. As a result, here’s what to remember if you’re just getting started with cakephp (again…).

Hint #1:

In your controller you find a variable called “$uses”. Normally, if you use a default setup you don’t need this. Cake will automatically associate your controller with the correctly named model. For instance if you have a controller named “UsersController” in the file “UsersController.php” and then have a model named “UserModel” in a file named “UserModel.php” in the models folder. Well cake is smart enough to figure that out. But let’s say I have “LoginController”…well I don’t want to rename it to “LoginsController” just to keep with tradition. So I can say in my controller:

var $uses = array(Login');

Then I can call $this->Login->find(); ¬†or whatever… Cake will associate my controller with the LoginModel class. I can also use cake’s “loadModel” function in my controller like this:

$this->loadModel('Login');
$this->set('data', $this->Login->find(null, '1'));

Hint #2:

Let’s say I make something called a “BouncerModel” which is supposed to act like a bouncer at a nightclub. He only allows people in who are on the list. Let’s also say I’m a giant retard (true) and I put all the users on the list in a different database. Well, in order for me to check some information about the users, my “Bouncer” needs access to call the other database…

There’s a special variable you can use for this:

public $useDbConfig = 'another_database_name';

This allows that model to use another database connection defined in your “database.php” file.

Hint #3:

You can respond to ajax calls with json easily in cakePHP, no need to set autorender to false for this one. Simply set the response type to json. Make an array of data, encode it in json with PHP and set the response body to the encoded array. Then send the response:

$this->response->type('json')

$r = array('data' => 'stuff', 'more_data' => 'more stuff');

$this->response->body(json_encode($r));

$this->response->send();

Easy enough!

Hint #4:

If you download the zip from github for cakePHP, and it gives the error “URL rewriting is not configured properly” then it’s most likely the .htaccess folder in your project root. Look here for more information. Basically, you need three .htaccess files. One in webroot. One in your “app” folder and finally another .htaccess file in your project root directory. The .htaccess in your project root should have this:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]
</IfModule>

Make sure you have all these files. Just to reiterate. The /htdocs/project/app/webroot/.htaccess:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

The /htdocs/project/app/.htaccess:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule    ^$    webroot/    [L]
    RewriteRule    (.*) webroot/$1    [L]
</IfModule>

And finally, the /htdocs/project/.htaccess:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]
</IfModule>

That’s it!

Hint #5:

If you cake application sends keep alive headers or seems to be hanging…you can stop it manually:

$this->response->send();
$this->_stop();

This will force ajax headers to stop with the keep-alive stuff…

Hint #6:

You forgot to add the “tmp” directory to .gitignore. You uploaded some tracked files, pulled with your other workstation and then realized your mistake. You removed your ignored files with:

git rm -r /absolute/path/to/directory

Now everything is peachy except for about a million errors on your normally 100% functioning cake app. Mostly permission based stuff saying file engine couldnt write to the file “access denied.” Well no worries. If you look at your default cake install under the tmp/cache directory you’ll see there are three folders “persistent”, “models” and “views”. Simply remove the cache folder completely, create a new “cache” folder with “persistent”, “models” and “views” as subfolders. Boom.

Hint #7:

Why gather specific form fields to submit with your ajax call, when you can simply serialize all the form data (as long as it was created with CakePHP’s htmlFormHelper). I’ll give an example. Let’s say I create the following form with cakePHP:

echo $this->Form->create('Hoody', array(
        'url' => array('controller' => 'hoodies', 'action' =>  'submit'),
        'type' => 'post',
        'label' => ''
    ));

    echo $this->Form->input('size', array(
        'id' => 'size',
        'type' => 'text',
        'label' => 'Hoodie Size',
        'value' => $hoody_size
    ));

    echo $this->Form->input('letter', array(
        'id' => 'letter',
        'type' => 'text',
        'label' => 'Hoodie Letter',
        'value' => $hoody_letter
    ));

    echo $this->Form->end('Submit');

Now I don’t need javascript to do a ton of heavy lifting here. I can simply stop the default behavior when someone hits the submit button:

$('#form').on('click', function(evt) {
   evt.preventDefault();
});

You knew that… Then I can submit the form to the correct url using jquery’s “post” function. Just make sure you serialize your data!

// gather form data
       var _form = $('#form');

        var data = _form.serialize();

        // submit to proper url
        $.post(_form[0].action, data, function(data) {
            console.dir(data);
            // wait for a response and take action
        }, 'json');

Not always that obvious but very useful.

More to come…

Leave a Reply

Your email address will not be published. Required fields are marked *