Archive for the ‘CakePHP’ Category

Beware of the underscore

Thursday, September 25th, 2008

Have you ever tried using underscores (_) in your controllers variables that you are passing to the view using a combination of Controller::set() and compact()? Well, if you did, you must have realized that they never make it there, right? I haven’t submitted it as a bug yet but here it is:

class SandboxController extends AppController {
    var $uses = null;
    var $layout = 'sandbox';
    function beforeRender(){}
    function index()
    {
        $foo = 'foo';
        $bar = 'bar';
        $foo_bar = 'foobar';
        $this->set(compact('foo', 'bar', 'foo_bar'));
        $john = 'john';
        $doe = 'doe';
        $john_doe = 'john_doe';
        $this->set(compact('john', 'doe'));
        $this->set('john_doe', $john_doe);
    }
}

Now, in your view:

echo $foo . "<br />";
echo $bar ."<br />";
echo $foo_bar ."<br />";
echo "<br /><br />";
echo $john ."<br />";
echo $doe ."<br />";
echo $john_doe ."<br />";

Finally, the returned output:

underscore-bug

Anyone knows if that’s how it’s supposed to act?

Update: there is a way to actually get those variables intact. Thanks to Taylor for pointing it out.

$this->set(compact($foo, $bar, $foo_bar), false);

HtmlSource - a new DBO driver for CakePHP

Thursday, December 6th, 2007

Ok, ok - I’ve been slacking on this blog again, but I will keep that for another post where I will announce some major changes I have been thinking of lately. For today, I’d like to introduce the new DBO Source Driver: HtmlSource - which is completely functional but still lacking some of the features I have planned for it.

So what’s an HTML DBO driver you ask?

Simply put, it’s a way to treat any HTML page like a database and be able to retrieve (scrape) certain parts using an SQL-like command:

SELECT href, title FROM a WHERE class="submit"

(more…)

GridHelper - for easy grids in CakePHP

Saturday, November 3rd, 2007

Been busy as hell and I’m afraid it will be like this for another month or so, but here is a quick one I felt like sharing because I hope it will be helpful to some.

Haven’t you ever wished to only have to write something like this in your views:

e($grid->create($results));
(more…)

Conventional solution for the visitors + AclComponent

Sunday, October 28th, 2007

At different places where I read about ACL, a common question that always comes early in the comments is:

Assuming ‘Guests’ users are unidentified web visitors, how do you handler their access rights? They don’t login, so they can’t be assigned an ARO and thus ACL will reject their access to any actions.
How do you handle ‘Guest’ user’s permissons if they are not logged in?
(more…)

Components used in Shells

Friday, October 26th, 2007

While working with Shells, most of the time I have some Tasks taking care of certain specific business logic each. Today, I had the need for a special Task. Special because it was actually a kinda duplicate of an existing Component, my quite useful but still incomplete to share, SerialComponent.

Like I just said, this Component is incomplete and I know that I will be making several changes in the coming month - so quickly, before thinking of duplicate code, good/bad cake or anything like that, I realized that I didn’t want to have 2 different classes to update every time. That been said, what’s coming next is my implementation of a Component inside a Task, which, I still don’t know if it makes a good or bad cake but it at least avoids most of the duplicate code. Maybe there is a better one I don’t know of that would entirely avoid that duplication but until then, the following works. (more…)

XSS prevention and general sanitization

Sunday, October 21st, 2007

Today, while lurking on irc, someone asked about field sanitization and how to avoid XSS attacks (cross site scripting for those who are wondering), something, every one of us should think about when developing an application. Truth is, that while CakePHP does an amazing job at making you ‘forget’ about SQL injections (since it takes care of that right out of the box), it doesn’t deter nor filter other ways like the infamous XSS unless you ask it to do so.

I won’t go over the different kinds of possible attacks, I believe a lot has already been documented but to make it short, if your application uses forms, cookies or accepts parameters directly from the URL and you haven’t thought about that, it’s time you start doing some research. You should never trust your users! (more…)

SQL query logs in CakePHP’s shells

Thursday, October 18th, 2007

When I was coding some shells today, and after getting used to the invaluable query logs when working with controllers/views, it didn’t take much to realize that one of my favorite features in CakePHP just stopped working. When I asked on irc, gwoo said it doesn’t work.

I needed those and I wanted to avoid having to use the MySQL logging, so I started digging in the code until I got it fixed. So, if you’re like me, and want to optimize every single call made to your database, there is only one line to edit and that’s in /cake/console/cake.php at the bottom of the ShellDispatcher::__bootstrap() method:

//remove this line
Configure::write('debug', 1);
For some reason, they just decided to overwrite the debug settings you made in your core.php - I think someone had it there and just forgot about it because it’s supposed to be showing those errors. If you look at DbSource::showLog(), you will notice that it already takes care of separating between queries made using the command line (shells) and the ones using the browser (http) to show lines instead of table rows…

I really can’t answer what’s the reason for overwriting my debug settings but so far, removing it, hasn’t affected anything else, so I’ll consider it fixed for now. You have any idea why it’s there?

Custom error handling in CakePHP

Friday, October 12th, 2007

One of CakePHP’s magic is the routing system: router, dispatcher, error handler.

All three are involved in handling every HTTP request made to the application. Some of the invaluable features of this routing system are the default missing controller/action/helper/component/etc. which saves any new comer to the CakePHP community lots of trouble when starting to bake stuff.

When I started looking into the system’s core for how to best handle custom errors, I stumbled on different things that I thought interesting to point out and a couple bugs (or uncleaned legacy lines of code). I also realized that it couldn’t do the basic stuff I needed to handle like logging errors and showing a specific error template for specific errors. So, let’s get to it. (more…)

SQL query opmitization for HABTM in CakePHP

Saturday, October 6th, 2007

My last SQL optimization post found no response from the CakePHP community; which makes me wonder how many are actually using ACL with large databases. Anyhow, the ticket was submitted and gwoo seemed to approve the results. I can also now confirm that the last suggested indexes will give another push to your performance:

ARO: alias ACO: model and foreign_key

Now what’s that about HABTM? While reading the source code for the Model class, I stumbled on the Model::_deleteLinks() method:

function _deleteLinks($id) {
   $db =& ConnectionManager::getDataSource($this->useDbConfig);
   foreach ($this->hasAndBelongsToMany as $assoc => $data) {
      if (isset($data['with'])) {
         $model =& $this->{$data['with']};
         $records = $model->findAll(array($data['foreignKey'] => $id), $model->primaryKey, null, null, null, -1);

     if (!empty($records)) {
        foreach ($records as $record) {
           $model-&gt;delete($record[$model-&gt;name][$model-&gt;primaryKey]);
        }
     }
  } else {
     $table = $db-&gt;name($db-&gt;fullTableName($data['joinTable']));
     $conditions = $db-&gt;name($data['foreignKey']) . ' = ' . $db-&gt;value($id);
     $db-&gt;query("DELETE FROM {$table} WHERE {$conditions}");
  }

} }

(more…)

Validation combined with i18n in CakePHP

Thursday, October 4th, 2007

Not too long ago, I wrote a quite lengthy ‘how-to use validation in CakePHP‘ post. Over the past couple of days, I had to work with a form that uses 2 models and for which i18n is combined with validation - using __() for error messages.

As I had imagined, including the magic i18n function in the Model::validate definition in my models didn’t work. However, there was the Model::beforeValidate() method that was brought to my attention by biesbjerg on IRC. Simple, no?. Creating a new method in my models User::loadValidation() and calling that with AppModel::beforeValidate() so it applies on all models. (more…)