Thursday, April 16, 2009

Integrate PHP Into JavaScript in CakePHP

Thursday, April 16, 2009 3

The Nuts And Bolts of Cakephp blog recently posted the article “Blend PHP and JavaScript in CakePHP” by Teknoid. He wrote about how to serve JavaScript files with some PHP content by using the $javascript->link() method. That is an interesting approach to PHP/JS integration. After reading his post, I started to consider some alternatives.

Basically, what it comes down to is that you can blend PHP and JavaScript by either the following:

  • Embed JavaScript directly in your view templates (maybe this doesn't mean much to you).
  • Place .js file in your app/vendors/js/ or vendors/js.
  • Use the technique explained in Teknoid's blog.

And here's another alternative, or a more standard way to output files in CakePHP. In this article I am going to explain in detailed steps the way to integrate PHP into JavaScript.

First, parseExtensions needs to be activated (app/config/routes.php).

 Router::parseExtensions('js');

Let’s assume a basic model:

<?php
class User extends AppModel {
    var $name = 'User';
}
?>

Create a table for the User Model with the following SQL:

create table users (
  id int(11) not null auto_increment,
  username varchar(32) not null,
  primary key (id)
);

insert into users (id, username) values (1, 'Jennifer');

Let's build our controller:

<?php
class UsersController extends AppController {
    var $name = 'Users';
    var $uses = array('User');
}
?>

Okay, nothing fancy so far. Let's keep going.

Include the RequestHandler Component in our $components array of either the Users Controller or App Controller:

var $components = array('RequestHandler');

Include the Javascript and Cache Helper in our $helpers array of either the Users Controller or App Controller:

var $helpers = array('Javascript', 'Cache');

As you can see above, yes we are going to use view caching with the Cache Helper. So we'll set 'Cache.check' to true (app/config/core.php).

Configure::write('Cache.check', true);

We'll add an empty action to the Users Controller, for the sake of this demonstration and load some JavaScript file:

function test() {}

Then add another action that renders a JavaScript file:

function alert($id) {
 
    if ($this->params['url']['ext'] != 'js') {
        exit;
    }

    $this->layout = 'gen';
    $this->ext = '.js';
  
    $this->set("cacheDuration", '1 hour');
  
    $data = $this->User->findById($id);
    $this->set('data', $data);
}

In the alert() method, we have changed the file extension from ctp to js so that we can benefit from the code coloring functionality on our text editor.

Now, our Users Controller looks like the following:

<?php
class UsersController extends AppController {

    var $name = 'Users';
    var $uses = array('User');
    var $components = array('RequestHandler');
    var $helpers = array('Javascript', 'Cache');

    function test() {}
 
    function alert($id) {
        if ($this->params['url']['ext'] != 'js') {
            exit;
        }

        $this->layout = 'gen';
        $this->ext = '.js';

        $this->set("cacheDuration", '1 hour');

        $data = $this->User->findById($id);
        $this->set('data', $data);
    }
}
?>

Okay. Let's move on to the view part. We need a view (views/users/test.ctp) to load a JS file:

<?php
if (isset($javascript)) {
    $javascript->link('/users/alert/1', false);
}
?>

The number in the end of the url indicates a user with id=1. So, we are going to retrieve an individual user's data record.

We'll create a layout for JavaScript output (views/layouts/js/gen.ctp):

<cake:nocache><?php header("content-type: application/x-javascript"); ?></cake:nocache><?php
echo $content_for_layout;
if (!$this->cacheAction) {
 $this->cacheAction = $cacheDuration;
}
$this->data = null;
Configure::write('debug', 0);
?>

And a basic view for the alert action (views/users/js/alert.js):

So, if you don't have a js folder in your /app/views/users, create one (this is where you place the alert view template ).

alert("<?php echo $data['User']['username']; ?>");

That's it! Now that we've got a dynamic JavaScript output with view caching, let's quickly open the page located at /users/test in our browser where the alert dialog will appear.

Wednesday, April 8, 2009

Preventing Duplicate Form Submissions in CakePHP

Wednesday, April 8, 2009 0

Forms are a necessary part of web applications and a great way to add data to your database. But somtimes this useful tool may cause problems if your visitors submit the same form information over and over again. How do you solve this with CakePHP or in Cake way? The solution is simple. CakePHP already has one built in, and it's really neat.

Using our Posts controller example, we can make use of Model::postConditions() together with Model::hasAny():

function add() {
 if (!empty($this->data)) {
  $this->Post->set($this->data);
  if($this->Post->validates()) {
   if ($this->Post->hasAny($this->postConditions($this->data))) { 
     $this->Session->setFlash(
      __("Duplicate form submissions are not acceptable.", true)
     );
   } else {
    if ($this->Post->save($this->data)) {
     $this->Session->setFlash(__("Your data has been saved.", true));
    }
   }
  }
 }
}

Hope this is helpful for some of you.

Friday, April 3, 2009

Directly Calling a Model Function from a View

Friday, April 3, 2009 2

It's always better not to call functions in the model from the view, because it breaks somehow the MVC pattern. However, there might be cases where this approach is needed.

A quick example would be:

class Post extends AppModel {

    var $name = 'Post';

    function user($id, $key = null) {
        if (empty($id)) {
            return null;
        }
        $user = ClassRegistry::init('User')->find('first', array(
            'conditions' => array('User.id' => $id),
            'recursive' => -1
        ));
        if (!$user) {
            return null;
        }
        if ($key == null) {
            return $user;
        } else {
           $user = array_pop($user);
           if (isset($user[$key])) {
               return $user[$key];
           }
           return null;
        }
    }

}

See the above example. The method user() is just a sample method that returns an entire User record for a given ID. In addition, if the second argument is given correctly, only a specific field will be retrieved from a returned row.

Now that we have a model function, we can call it in our view:

<? pr( Post::user(1) ); ?>
<? pr( Post::user(1, 'username') ); ?>

Saturday, March 28, 2009

Zodiac Sign Helper Class for CakePHP

Saturday, March 28, 2009 0
This is a simple Helper class for CakePHP that determines what is the zodiacal sign that corresponds to a given date or datetime string.

Releases:

  • Major version released. 1.0.0.0 (New!)

Requirements:

  • CakePHP 1.2 (not tested with CakePHP 1.1.x.x)
  • PHP versions 4 and 5

Licese:

Download:

Installation:

Example Usage:

In your view, just call the ZodiacSignHelper::name(). The passed argument must be a valid date or datetime string. And you will get a Sun zodiac sign such as Virgo, Leo and Sagittarius:

echo $zodiacSign->name($data['User']['birthday']);

You can also get a Chinese zodiac sign by setting the second parameter to 'Chinese'. The Chinese Zodiac consists of a 12-year cycle, each year of which is named after a different animal that imparts distinct characteristics of its year. For example, the year 2009 is the Year of the Ox:

echo $zodiacSign->name($data['User']['birthday'], 'Chinese');

Thursday, March 26, 2009

A More Secure Way to Transfer Session State Between CakePHP Applications

Thursday, March 26, 2009 2

In a previous article entitled "Sharing Session State Across CakePHP Applications", I wrote about the way to transfer session IDs between CakePHP applications. Thanks to the CakePHP development team, CakePHP already has secure session handling; however, some might even think that it is not secure to append a session ID to links. I hear say some search engines indexes URLs with session IDs. Isn't it horrible? One obvious solution would be not to assign them to any of the links on pages.

Let's say we have two sites, siteA.com and siteB.com. We need to maintain a user's session state (authenticated with the Auth Component) when the user jumps from siteA.com to siteB.com by clicking some link.

First, we need to do some settings:

  • Set 'Security.level' to 'low' on siteB.com.
  • Set the session handling method ('Session.save' in app/config/core.php) to 'database'.
  • Use the same Security.salt (/app/config/core.php) for each application.

We are going to use the same session database table for both sites.

Use the CakePHP console to create your session database table:

$ cake schema run create Sessions

Yeah, it's always fun to run the cake console, but you can also use the SQL file found in app/config/sql/sessions.sql.

Create a SiteTransfer Model for each application (on siteA.com and siteB.com):

class SiteTransfer extends AppModel {
    var $name = 'SiteTransfer';
}

Basically the table structure looks something like this:

create table site_transfers (
 id varchar(36) not null,
 sess_id varchar(26) not null,
 primary key (id)
);

In our Users Controller on siteA.com:

class UsersController extends AppController {

  var $name = 'Users';
  
  function index() {}

  function redirectem() {
    $this->autoRender = false;
    App::import('Core', 'String');
    $data['SiteTransfer']['sess_id'] = $this->Session->id();
    $this->SiteTransfer->id = String::uuid();
    if($this->SiteTransfer->save($data)) {
      $this->redirect(
        'http://siteB.com/users/catchem?uuid='.$this->SiteTransfer->id
      );
    }
  }

} 

We have a link saying ‘Go to siteB.com’in the index.ctp view:

echo $html->link('Go to siteB.com', array(
  'action' => 'redirectem'
));

Let's see what's going on here…
When the user on the Index page on siteA.com clicks the link, we redirect the user to the redirectem() action (this action does not need any view). In the 'redirectem' method, we get the current session ID and save it into our site_transfers table with a UUID (i.e. String::uuid). Then we do a redirect to /users/catchem on siteB.com.

Alright, let's build a Users Controller for siteB.com:

class UsersController extends AppController {

  var $name = 'Users';
  var $components = array('Session');

  function beforeFilter() {
    if(!empty($this->params['url']['uuid'])) {
      $uuid = $this->params['url']['uuid'];
      $data = $this->SiteTransfer->findById($uuid);
      $this->Session->id($data['SiteTransfer']['sess_id']);
      $this->SiteTransfer->del($uuid);
    }
  }
  
  function catchem() {
    $this->redirect(array('action' => 'index'));
  }

  function index() {
    pr($this->Session->read('Auth')); 
    exit; 
  }

} 

What happens when the user gets to siteB.com?.
We search our database table (site_transfers) for the UUID token, and then instantiate the session with the session ID from the database. Finally, for security purpose, we need to delete the UUID and session ID from our site_transfers table.

All done! So now the user is logged into both siteA.com and siteB.com.

Saturday, March 21, 2009

Sharing Session State Across CakePHP Applications

Saturday, March 21, 2009 0

This is a pretty simple tip, but I thought I might want to document this somewhere like the gotcha page. I'll show you how to share session state across multiple CakePHP applications. It's as easy as 1-2-3.

Let's say we have two sites, siteA.com and siteB.com. A user is browsing siteA.com and we want him (or her) transferred to siteB.com. The user should be already authenticated before jumping to siteB.com.

There are some settings you must first configure:

  • Make sure that you have set 'Security.level' to 'low' on siteB.com. Notice that 'high' and 'medium' will mark the embedded session ID as invalid.
  • Set the session handling method ('Session.save' in app/config/core.php) to either 'php' or 'database'. Both applications must have the same session handling method and access to the same session storage (and therefore the same session).
  • Use the same Security.salt (/app/config/core.php) for each application.

In our view template on siteA.com, append the session ID to the link like the following:

echo $html->link('Go to siteB.com',
 "http://siteB.com/tests/index?sid=" . $session->id()
);
On the other end (siteB.com), use $this->Session->id($this->params['url']['sid']) in the beforeFilter method of your controller:
function beforeFilter() {
  if (!empty($this->params['url']['sid'])) {
    $this->Session->id($this->params['url']['sid']);
  }
}

When the user clicks the link on siteA.com, it'll redirect with the session id as parameter and instantiate a new session.

If you need a more secure way, go check the next post “A More Secure Way to Transfer Session State Between CakePHP Applications

Monday, March 16, 2009

Utilizing the AppController::beforeRender to Assign CakePHP's Controller Attributes

Monday, March 16, 2009 0
This may be a matter of preference, but I think it's a pain to assign CakePHP's controller attributes to all views in my controllers. So I always do this in my applications.

Add a $this->set into the AppController::beforeRender to always read $this->data.
class AppController extends Controller {
function beforeRender() {
 if (!isset($this->viewVars['data'])) {
  $this->set('data', $this->data);
 }
}
}
In your controller (any controller that extends the app controller), you don't have to assign $this->data any more.
class PostsController extends AppController {
function index() {
 $this->data = $this->paginate();
}
}
In this manner, you can also do something like the following:
function beforeRender() {
 if (!isset($this->viewVars['data'])) {
  $this->set('data', $this->data);
 }
 if (!isset($this->viewVars['modelClass'])) {
  $this->set('modelClass', $this->modelClass);
 }
}
Now, you can access them anywhere in views with $data and $modelClass.
<? if($data): ?>
<? pr($data)?>
<? endif; ?>

<? if($modelClass): ?>
<? pr($modelClass)?>
<? endif; ?>
 
JamNite ◄Design by Pocket, BlogBulk Blogger Templates