Simple value getter and setter for CakePHP

This snipped I’ve wrote, because I think it’s convenient to have something like this in cake.

Put this in AppModel (/youur_cake_project/app/app_model.php)

<?php
class AppModel extends Model {
    /**
     * handy method for getting and setting value in a model.
     * For setter: it's not validating anything, so bear in mind...
     * Usage:
     *   Getter:
     *    $this->MyModel->id = 5;
     *    $this->MyModel->value('name'); //retun value of column name for the id 5
     *   Setter
     *    $this->MyModel->id = 5;
     *    $this->MyModel->value('name', 'BlaBla'); //set the name of row with id 5 to BlaBla
     */

      public function value($field, $value = null){
    if(func_num_args() == 1){ //getter
        $result = $this->field($field);
        if($result){
        return $result;
        }
    } else { //setter
        if($this->saveField($field, $value)){
        return true;
        }
    }
    return false;
     }
}?>

Getter:

$this->YourModel->id = 5; //set the id of the model
$this->YourModel->value('name');//return the value of the row with id 5

Setter:

$this->MyModel->id = 5; //set the id of the model
$this->MyModel->value('name', 'BlaBla'); //set the name of row with id 5 to BlaBla

As you can see it’s not a rocket science, and it’s uses cake’s functions for this, but I thought it’s convenient to have such function.

Share it:
  • Facebook
  • Twitter
  • Digg
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
  • Yahoo! Buzz
  • Add to favorites
  • Identi.ca

Extending CakePHP Facebook plugin

Currently I am working on an application which require Facebook authentication for it’s users. As you may guess its written in CakePHP, and I’ve searched on Internet for a plugin which integrate Facebook in CakePHP application.

There is one very good CakePHP Facebook plugin written from Nick Baker, and I give a try. It’s really good plugin which provides everything for integration of Facebook (even the Facebook API) in your site. Full list example of functionality can be seen here.

Although, I’ve notice that the site is getting slow when the user is connected on the Facebook. Digging in the code I’ve noticed that the initialize() function which is responsible for the initialisation of the plugin request every time the data for the logged user from the Facebook, and this of course slows down the Application itself, because initialize() is called on every page refresh in every site.

What I’ve did – a little optimisation of the code. Here is the explanation how the improved core works:

  1. on init (initialize() function) it just assign the FB instance to the component and getting the Facebook session. This doesn’t require FB call.
  2. There is an extra parameter which could be provided to the plugin’s settings – noAuth. If this parameter is set the plugin wont attempt to login using the Auth component in the site. By default this parameter isn’t set, but it’s more convenient to have it, because in some cases like mine, I don’t use user Auth on the site except the Facebook’s. Here is a sample how to set noAuth for the plugin:
    class AppController extends Controller {
    $components = array('Facebook.Connect'=&gt;array('noAuth'=&gt;true));
    }
  3. Finally in your AppController::beforeFilter() you can use following in order to get the logged user’s details:
    class AppController extends Controller {
    function beforeFilter(){
    $fb = $this-&gt;Connect-&gt;user();
    }
    }

    This call has been already cached and you don’t need to worry about extra calls to Facebook site.

Another think which I’ve seen in the comments for the Nick’s article is the request to disconnect (unsubscribe) from the application without logging out of the Facebook. That’s why I’ve added a function disconnect() which doing exactly this.

Usage:

<?php
    echo $this->Facebook->disconnect(array(
                     'label'=>__('exit', true),
                     'confirm'=>__('Are you sure?', true)
                     ));
    ;?>

Possible options which could be provided in the function:

  • label – string text for the link
  • redirect – action to which user will be redirected after the logged out. If it’s not set the page will be reload.
  • confirm – javascript confirm message (for example “Are you sure?”) before user disconnected from the application.

I’ve added the confirm option in the logout as well (with the same functionality), as well as there is a new option parameter custom which will force the link creation instead or fbml logout link, because in the original implementation custom link is used only if you pass redirect action, but in some cases it need only to reload the page without any redirection and it’s convenient to have a custom link.

And finally where is the extended plugin? Of course in guthub. CakePHP-Facebook-Plugin

Update: The changes are already accepted and included in the original author of the plugin and you can found them at Plugin’s home page

Share it:
  • Facebook
  • Twitter
  • Digg
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
  • Yahoo! Buzz
  • Add to favorites
  • Identi.ca

CakePHP saveAll() quick tip

Saving data with Model->saveAll() is really time savior. There is something specifics while saving multiple records of a single model.

The data provided from the form should be in the numerically indexed array of records like this:

Array
(
    [Article] => Array(
            [0] => Array
                (
                            [title] => title 1
                        )
            [1] => Array
                (
                            [title] => title 2
                        )
                )
)

Your code for saving this data with saveAll() should look like this:

$this->Article->saveAll($data['Article']);

Ok, but if you pass only

$this->Article->saveAll($data);

it won’t work. So if you want to save multiple records of a single model provide the proper data. It took me 1/2 hour to detect that this is the problem.

Of course this is written in the CookBook, but somebody need to read it carefully 😉

Share it:
  • Facebook
  • Twitter
  • Digg
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
  • Yahoo! Buzz
  • Add to favorites
  • Identi.ca

CakePHP: CakeMenu plugin

I am using it for a while, but today I’ve decided to publish in the github.com.

What this plugin does?

The plugin is complete solution to add menu in your applications. It uses the nifty Superfish – jQuery menu plugin. You can find more info for it at http://users.tpg.com.au/j_birch/plugins/superfish/

Cakemenu can work with multilevel menus and reduces the database calls by caching the menu nodes. The plugin working with Authake plugin if you need to apply filter to menu nodes (user need to see only allowed locations)

Cakemenu working with CakePHP 1.2 but it’s tested with Cakephp 1.3 (RC3) and it would not have any problems with the future releases so far.

Requirements

  • CakePHP 1.3 (of course)
  • jQuery in the head tag
  • Authake (optional) if you require your menu nodes to be filtered when user with limited privileges is logged in. Actually it’s possible to use other authorization class, but you have to extend it.

I believe that’s it. Check the large README file in the project’s directory.

Share it:
  • Facebook
  • Twitter
  • Digg
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
  • Yahoo! Buzz
  • Add to favorites
  • Identi.ca

CakePHP: Authake plugin with installation guide

Finally the Authake Plugin have an Installation guide.

Basically the plugin provide Authentication and Authorization functionality for CakePHP’s appliation with few line of code. Authake has advanced User-Group-Role interface and allow you to secure your CakePHP’s application within a minute.

The current version of the Plugin is “wrapped” in a single folder (according to CakePHP 1.3 conventions) under the Plugins.

Update: This plugin has been addapted for CakePHP 2.0 by Mutlu Tevfik Kocak. Please use his repository for actual version of the plugin. https://github.com/mtkocak/authake

Share it:
  • Facebook
  • Twitter
  • Digg
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
  • Yahoo! Buzz
  • Add to favorites
  • Identi.ca

isUnique validation of limited length field

Working on a project I had following problem.

I had to set isUnique validation of a field. The field has VARCHAR(10) type. When I save the data the “isUnique” validation doesn’t work as expected while I was sure that the there is such record in the database. Digging through the problem it turn out that the problem is in the length of the DB column.

Let me explain. The field was length 10, but in the form I’ve put the value which is 11 characters long, so when the first data is submitted instead of the 11 characters, only 10 are saved in the DB table. My value was 456-23-2010 while in the db it’s saved 456-23-201.

So when inserting the new data the script checks 456-23-2010 against the database where is stored 456-23-201. and of course it passes the validation. While on the edit action strangely it appear that the value it is not unique any more (because there are already 2 records 456-23-201 in the db. 🙂

A little bit tricky, because at first glance the data is almost the same. For sure if the inserted string was large than the saved in the DB I would spot it easily, but to me the number was really the same.

There are 2 possible ways where I would think how to solve this problem in the future: Either modifying the Bake template for my applications, or using better validation technique – where the value is trimmed up to length of the field.

I was wondering what would be the better way?

Share it:
  • Facebook
  • Twitter
  • Digg
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
  • Yahoo! Buzz
  • Add to favorites
  • Identi.ca

Online html to pdf tool

html to pdf converter I just want to present a new tool for converting HTML to PDF – html-2-pdf.com. It’s basically an online converter which could transform any* web site to a PDF document. Generally it could be useful if you want to print a website, or for example if you want to save the content of the website for offline reading.

The site is really simple – just insert the address of the web page which you want to be converted and few seconds after that it is ready to be downloaded. The site is just an interface of the amazing wkhtmltopdf library.

I am open for suggestions about the functionality of the site.

* – for some reasons there are web sites which are not converted correctly. This is because of HTTP headers which these sites restricting.

Share it:
  • Facebook
  • Twitter
  • Digg
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
  • Yahoo! Buzz
  • Add to favorites
  • Identi.ca

Careful with the links in the layout

When you building application most likely there are common links within the layout. They could be in a menu, or let’s say “edit profile” and ‘logout’ links which are visible everywhere. As you probably know if you use Html Helper the link could be either Cake-relative URL or array of URL parameters.

The problem may occur if you using the second option – the array.
Continue reading

Share it:
  • Facebook
  • Twitter
  • Digg
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
  • Yahoo! Buzz
  • Add to favorites
  • Identi.ca