CakePHP 3: Access a method from one Behavior (or the Table class) in another Behavior

Please note that this post refers to CakePHP 3.

Short answer is, as long as you have added both Behaviors in the Table class, you can call a method from one Behavior in another as follows:

class SecondBehavior extends Behavior {
    public function secondBehaviorMethod() {
        return $this->_table->firstBehaviorMethod();
    }
}

I couldn’t find anything about this in the docs, so initially I hoped/presumed that, as long as I had added both Behaviors to my Table class, it was simply a case of calling the method as I would in a Table, so:

In MyTable.php:

public function initialize(array $config) {
    ...
    $this->addBehavior('FirstBehavior');
    $this->addBehavior('SecondBehavior');
}

In FirstBehavior.php:

class FirstBehavior extends Behavior {
    public function firstBehaviorMethod() {
        return "done";
    }
}

In SecondBehavior.php:

class SecondBehavior extends Behavior {
    public function secondBehaviourMethod() {
        return $this->firstBehaviorMethod();  //Gives "Call to undefined method" error
    }
}

However, this just results in a “Call to undefined method” error. However, Behaviors have the $_table property (see the Behavior API) that allows you to access other methods of the current Table. Therefore, just adding _table to the call to firstBehaviorMethod ($this->_table->firstBehaviorMethod()) fixes the issue. As well as accessing methods from other added Behaviors, you can also use find ($this->_table->find(…)), etc.

CakePHP 3: Date/Time Disappearing during Hydration

When generating a date/time for saving to a MySQL database, I’ve always tended to generate it with the PHP date method (date('Y-m-d H:i:s')). However, using CakePHP 3, with dateTime validation set on the field, the date/time would disappear during hydration of the entity, but without a validation error.

I still suspected that validation was the issue here, so started having a look at the validation method to try to work out what was going wrong. Before I got very far, I noticed that the datetime validation method validates any value that is a Cake DateTime object. Therefore, the simple solution is to create the date/time using Cake’s built-in Time class:

use Cake\I18n\Time;
$datetime = Time::now();

Cake then happily saves the DateTime in the standard MySQL format.

CakePHP: Getting the full URL of the current page

In a CakePHP (2.3) project, I needed to echo the full (i.e. including scheme (http, https etc) and hostname) current URL in a view. I assumed this would be easy, and it is, but it wasn’t immediately obvious and took a bit of searching. The following examples assume we are on localhost, the project is called ‘project’ and the current page is /controller/action/1, so we would expect the full URL to be: http://localhost/project/controller/action/1.

The way to do it:

All we need to do is to echo a null url, with the ‘full’ option set to true, which means the scheme, hostname and project path are included. As well as null, any “falsey” value seems to work, e.g. false, 0, “”, and even array().

echo $this->Html->url(null, true);

Produces: http://localhost/project/controller/action/1

The ways not to do it:

echo $this->here;

Produces: /project/controller/action/1. This is missing the scheme and hostname.

echo $this->Html->url();

Produces: /project/controller/action/1. Again, this is missing the scheme and hostname.

echo $this->Html->url( $this->here, true );

Produces: http://localhost/project/project/controller/action/1. Here ‘project’ appears twice, once from $this->here and once as we have set the ‘full’ option to true.

XML views in CakePHP 2.x

In a CakePHP project, I needed to extract an XML string from the database and display it as an XML page. The docs suggested this would be easy with the XmlView, but I struggled to get it to work. However,  after a fair amount of fiddling around, I found an easy way to display an XML view.

Here’s what I had to do:

  • Enable parsing of .xml extensions in routes.php:
    Router::parseExtensions('xml');
  • Set the viewClass to Xml in the controller:
    $this->viewClass = 'Xml';
  • Create a simple xml view in Views/YourController/xml/xml.ctp, and echo $xml in this view:
    <?php echo $xml; ?>
  • Back in the controller, set the XML string to the view:
    $this->set('xml', $xmlString);
  • Finally, render using the xml view you have just created (this must be after the ‘set’ line above):
    $this->render('xml');

Unfortunately, this does not take advantage of the _serialize key, which would mean you don’t need to create a view file at all, but I just couldn’t get this to work with an XML string, despite trying various combinations of CakePHP’s Xml Class functions.

Complete Idiots Guide to using Composer with CakePHP

I recently wanted to use Miles Johnson’s Forum Plugin for CakePHP in a project, and when I came to install it, saw that he recommends (insists on, in fact) using Composer to do this, to take care of ensuring all the dependencies are installed. Never having used Composer before, I took a look at his post on using Composer with CakePHP, which probably counts as an idiots guide for most people, but still wasn’t basic enough for me. Therefore, I thought I would write a complete idiots guide!

The steps I had to go through to get it working were as follows:

  • Install Composer – I am on Windows, so just downloaded and ran the Windows installer, which seemed to work fine
  • Ensure that the openssl extension is enabled in php.ini, i.e. uncomment this line: extension=php_openssl.dll
  • Create a composer.json file in your app directory and add the dependencies, e.g. for the Forum plugin:
    {
       "config": {
          "vendor-dir": "Vendor"
       },
       "require": {
          "mjohnson/forum": "5.*"
       }
    }
  • Run composer install in the app directory. This should install all of the dependencies (in the Vendor or Plugin directories of your app, as appropriate) and create an autoload.php file in the Vendor directory
  • Add the following at the start of your Config/core.php file to make use of Composer’s autoloading capabilities:
    require_once dirname(__DIR__) . '/Vendor/autoload.php';

That should deal with all of the dependencies, in this case for the Forum Plugin. It is still necessary to load the Plugins in the Config/bootstrap.php file. For the Forum Plugin, this is does as follows:

CakePlugin::load('Utility', array('bootstrap' => true, 'routes' => true));
CakePlugin::load('Admin', array('bootstrap' => true, 'routes' => true));
CakePlugin::load('Forum', array('bootstrap' => true, 'routes' => true));

CakePHP/MySQL: Want a Boolean? Use TINYINT(1), not BIT(1)

I was recently creating some new MySQL tables that stored booleans, so I thought I would do things (what I presumed to be) properly and make them BIT(1) columns, rather than TINYINT(1). However, when I came to try to save values to this field using CakePHP, everything was saved as 1, even if the value in the data array was 0, false, “”, “0” or anything else ‘zero-ey’ or ‘falsey’.

It turns out that BIT fields are not supported by Cake, and so you should just use TINYINT(1) instead!

Furthermore, Cake will assume a TINYINT(1) field is intended as a boolean field, and will only allow you to assign it a value of 0 or 1, even though TINYINT(1) can store values from -128 to 127 (or 0 to 255 unsigned). If you try to save any value other than 0 or 1 to this field, it will be saved as 1 (but note that false, “” and an empty array will cause a save error).

Eclipse: Adding File Associations

We regularly write PHP, using the CakePHP framework, in Eclipse (Juno, with PHP Development Tools (PDT)). The view template files in CakePHP have the .ctp extension, which Eclipse does not, by default, recognise as PHP files, so you do not benefit from any of the helpful Eclipse PHP tools. However, you can add an association (i.e. tell Eclipse that .ctp files are PHP files), as follows:

  1. Go to Window > Preferences to open the Preferences box
  2. Go to General > Content Types in the menu
  3. In the Content types box, expand Text and select “PHP Content Type”
  4. Click “Add”
  5. Type “.ctp” in the box that appears and click OK
  6. Click OK to close the Preferences box

Note that you will have to close and then reopen any .ctp files that are already open in order for them to be recognised as PHP files.

CakePHP not saving to new field on production server

I wasted a few hours on Saturday morning struggling with the fact that CakePHP on my production server refused to save to a newly added field on a table in my database, while everything worked beautifully on my dev server. After hours of debugging on the live server I suddenly remembered that, with:
Configure::write('debug', 0);
in core.php, as it should be on a production system, Cake uses the cached model definitions in tmp\cache\models and would therefore ignore any changes in the underlying database until these were refreshed. Simply either:

  1. Change temporarily to Configure::write('debug', 2); and then run your code before changing it back again or;
  2. Delete the contents of tmp\cache\models

and it will pick up your new field.