CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

Using the CakeDC Tags plugin for CakePHP

This is an introduction to using the CakeDC Tags plugin for CakePHP. I'll take you through a new project creation, and the addition of the Tags plugin to your project for use with tagging a Blog model on your project. You should be able to take the skills learnt here to any other project, and start taking advantage of the Tags plugin for tagging your models appropriately. Lets get started by baking a new project: cake bake project blog1 Follow the prompts to complete the baking operation. You will now have a "blog1" directory available. Change into that directory: cd blog1 ensure that the `tmp` directory is writable: chmod -R 777 tmp Open up the `config/database.php.default` file in your favourite editor. Immediately choose to "Save as..." and save the file in the same location omitting the ".default" part of the filename. So save the file as `config/database.php`. Configure the options at the bottom to match the database credentials for your application. Mine are as follows: <?php class DATABASE_CONFIG { var $default = array( 'driver' => 'mysql', 'persistent' => false, 'host' => 'localhost', 'login' => 'dev', 'password' => 'dev', 'database' => 'blog1', 'prefix' => '', ); } For the moment, I have remove the 'test' datasource, as we won't use that right now. Go ahead and create your MySQL database, and a simple table to hold blog items: CREATE DATABASE `blog1`; USE `blog1`; CREATE TABLE `blogs` ( `id` CHAR(36) NOT NULL PRIMARY KEY, `title` VARCHAR(255) NOT NULL, `body` TEXT, `created` DATETIME, `modified` DATETIME ); Now lets bake the controller, model and views for this blogs table, in order to be able to add and edit content. Once this is complete, we'll begin integrating the tags plugin into the application. First bake the model: cake bake model blog Next bake the controller. The following bakes all the "public" actions for this controller: cake bake controller blog public And finally, the views: cake bake view all Browse around your application at the address: /blogs to begin with to ensure that your app is functioning correctly. You should be able to add, edit, delete and view blog entries. Time to get cracking on the Tags plugin. Our objective here is to tag each blog entry with an arbitrary tag at add / edit time to allow us to easily categorise content we are posting. In order to download and install the Tags plugin, I'll be using git. You can however download an archive from the github website, and extract that archive into your `APP/plugins` directory. In either case, the result will be a `tags` directory in your `APP/plugins` directory, containing the contents of the CakeDC tags plugin. From your `APP` directory (in this example, the APP directory is `blog1`), clone the tags repository: git clone git://github.com/CakeDC/tags.git plugins/tags The first thing that we need to do now that the Tags plugin has been added to our project, is to create the tables required to store the tag information. These are available in schema's and migrations within the Tags plugin, so you don't need to handle the SQL yourself, just use the cake console to create the tables for you: If you prefer using the builtin CakePHP schema mechanism, or you are not sure what the "migrations" plugin is, you can create the database tables like this: cake schema create schema -plugin tags -name tags If however, you are familiar with using the migrations plugin, or you want to use the migrations plugin for this project, add the migration plugin to your project, and then run the migrations: git clone git://github.com/CakeDC/migrations.git plugins/migrations cake migration -plugin tags all Either method is fine. Next up, we need to add the `Taggable` behavior from the `Tags` plugin to our model to enable all the awesome functionality. Add the following variable to your `Blog` model in `APP/models/blog.php`: public $actsAs = array( 'Tags.Taggable' ); Finally, we need to add a new input for the tags on our add and edit screens, to allow users to customise the tags they want for the blog posts. Simply add a new input called 'tags' to your forms, such as the following: echo $this->Form->input('tags', array('type' => 'text')); Note that this needs to be done for both your add and edit views. You can also make this be of type `textarea`, if you need gigantic amounts of tags. `text` is fine though, to allow a good number of tags, and to minimise the input space. This is all you need to do to enable your content to be tagged! Looking back at all the instructions so far, the bulk of the content has been on how to create a new project, bake the model, views and controller, and the addition of plugins. In terms of code addition, we've only added a behavior to the Blog model, and a new input to the add and edit views. To test your tagging, use a comma to separate your tags when using the tags input. Using a comma allows you to enable users to add multiple-word tags. What now!? You can tag stuff, thats pretty cool. You probably want to look up blog posts based on tags now. Thats already provided for you in the Tags Controller quick comes with the Tags plugin. Browse to `/tags` to see the tags controller index action from the tags plugin render all the tags that you have added to your blog so far. There is a whole lot more that you can do with tagging in terms of both operation and the visual representation of the tags themselves. Stay tuned for more blog articles explaining our plugins and other interesting PHP and CakePHP code from myself and the rest of the CakeDC team. UPDATE: An excellent guide on how to style the tags with CSS has been written by @WyriHaximus, check it out here.

Utils Plugin release v1.1

The Utils plugin is our mixed bag of "awesome". If you've not yet checked it out, definitely hop over to github to check it out. It aggregates a lot of useful code and miscellaneous ideas into a single plugin thats portable and dead easy to use in your applications. Since its release in September, we've made a few changes and updates, and we've bundled a new version for release. Here's a summary of the commits:

  • Commit [7bdf401]: Update license and readme.
  • Commit [e7630bd]: Added tests for data retrieval and false return from model delete.
  • Commit [8510fe4]: Updated documentation for Soft Delete tests.
  • Commit [f7d9983]: Removed empty test file.
  • Commit [c5db61b]: Changed the behavior saving the position manipulation without running model callbacks and validation by default. This is now also configureable by setting 'callbacks' and 'validate' in the behavior settings to true/false.
  • Commit [ca98003]: updating readme
  • Commit [edc6576]: updating readme
  • Commit [da6ec86]: Add a russian translation
  • Commit [a2319ca]: Adding spanish translation
  • Commit [752f1d7]: Added a Portuguese translation
The release is available now on the master branch of the repository, or you can download a release archive here. Don't forget if you have any issues, suggestions or fixes for the utils plugin, you can lodge a ticket on the ticket tracker at LighthouseApp. Enjoy!

CakeDC Plugins updates, October 2010

Its been a little while since we launched our plugins at CakeFest 2010 to the community, and a few things have been changed and updated in that time, so its time to throw out a new release for the community. We have received a huge response after opening our code to the community, and we're absolutely thrilled to know that you're taking advantage of the experience and effort that CakeDC has put into making these plugins. Getting feedback and hearing stories about usage makes it all worthwhile. The team has been monitoring tickets, and cleaning up where we can in-between "real work" :) Thanks to everyone that lodged tickets, submitted patches, we're overwhelmed with the generosity that people have shown by contributing to help benefit the community and to further the work we began. This blog marks the beginning of a run of updates we're doing with the plugins that have been released. We'll process tickets, package and release new versions every couple of weeks to ensure we're on top of tickets, and getting any updates published for people to use on a regular basis. We hope you enjoy the upcoming releases, and thanks again for the support! From all the team at CakeDC.

i18n routes with CakePHP 1.3

Internationalizing a CakePHP application can be tricky when it comes to deal with i18n urls. We will see in this article how the Custom route classes introduced by CakePHP 1.3 could be used to add the current language to your urls in a few lines of code. EDIT: This proof of concept has now been improved and a better version of the code below can be found in CakeDC's I18n plugin on Github

Requirements

This article will not go too deep in internationalizing an application as many resources already exist about it. We suppose the following:
  • Your application defines the current language on given the language code passed in the url
  • The available languages are configured via Configure::write('Config.languages', array('eng', 'fre', 'deu'));
  • You use the CakePHP array syntax for defining urls:
    • $this->Html->link('link', array('controller' => 'posts', 'action' => 'view', $post['Post']['id']));
    • $this->redirect(array('controller' => 'posts', 'action' => 'index'));
    • Router::url(array('controller' => 'posts', 'action' => 'index'), true);
Custom routes were already introduced by Mark Story on his blog, so we will not do it again here... before continuing be sure you have read "Using custom Route classes in CakePHP"

Show me some code!

I18nRoute

As I said (or not), routes are probably the best place for customizing your urls and add information in them... much more better at least than overriding the Helper::url() method in an AppHelper class! Custom routes introduced a way to customize how routes are processed in a very easy and powerful way (i.e ~20 lines of code). It is a bit like wrapping the Router class in CakePHP 1.2, a good example of this was the CroogoRouter. First, we are going to create an I18nRoute class extending CakeRoute in the "/libs/routes/i18n_route.php" file. Here is its code: <?php class I18nRoute extends CakeRoute { /** * Constructor for a Route * Add a regex condition on the lang param to be sure it matches the available langs * * @param string $template Template string with parameter placeholders * @param array $defaults Array of defaults for the route. * @param string $params Array of parameters and additional options for the Route * @return void * @access public */ public function __construct($template, $defaults = array(), $options = array()) { $options = array_merge((array)$options, array( 'lang' => join('|', Configure::read('Config.languages')) )); parent::__construct($template, $defaults, $options); } /** * Attempt to match a url array. If the url matches the route parameters + settings, then * return a generated string url. If the url doesn't match the route parameters false will be returned. * This method handles the reverse routing or conversion of url arrays into string urls. * * @param array $url An array of parameters to check matching with. * @return mixed Either a string url for the parameters if they match or false. * @access public */ public function match($url) { if (empty($url['lang'])) { $url['lang'] = Configure::read('Config.language'); } return parent::match($url); } } The most important part of the code is in the "match()" method. We just add the current language to the url "lang" named param if it was not set. The constructor was also overriden to add a regex pattern for the "lang" param. Thus, only lang prefixes defined in your list of available languages will be parsed by the route.

Define your routes

It is now time to use this custom route in your application. Here is how the default route for pages could be defined in "/config/routes.php": App::import('Lib', 'routes/I18nRoute'); Router::connect('/:lang/pages/*', array('controller' => 'pages', 'action' => 'display'), array('routeClass' => 'I18nRoute'));
  1. import the library file containing the custom route
  2. add a ":lang" param in where you want the language code appear in the url
  3. tell the Router you want to use this custom class (third param)

Link from everywhere!

Now you won't have to worry about the language code transmitted in your urls... every generated link will contain the current language code. If you want to switch the language (for instance switching to the French version of your application), you will just have to add the "lang" param to the url array. Here are some examples of urls which would be generated on the "/eng/posts/index" page: $this->Html->link(__('French', true), array_merge($this->passedArgs, array('lang' => 'fre'))); // /fre/posts/index $this->Html->link('link', array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); // /eng/posts/view/2

Disclaimer

This code is experimental and the article shows you how to use CustomRoutes to implement this basic feature. Many improvements could be added to fit your needs (no language code for the default application lang, short languages code...) Even if the tests we made were successful, we have not used this code in production yet so there may be "real word" use cases that are not handled correctly with this solution... if you find one, please tell us in the comments!

Feature rich, customizable comments pl...

Freshly baked by the friendly team here at CakeDC is the Comments plugin. For those of you too impatient to read on for a description, grab the goods here. And checkout the Sample Application. The comments plugin allows you to enable comments on any controller for any existing model in you application. Built in a manner to allow complete separation from your application, enabling and including the comments functionality is almost too easy. A good use case is the addition of comments to blog posts. In this case you can facilitate user feedback on information posted on your web site to further enhance the facilities of your existing application. The documentation takes you through a practical example of how you can include this into an existing application with only a couple of code lines. Checkout the documentation here.  

We Bake with CakePHP