CakePHP ACL Behavior modified
I’ve posted this up at the bakery, but articles seem to take awhile to get published. It could also be that they’re working on a new ACL Behavior, one can hope. For the time being, I’ve fixed up the core behavior and added a few features as well. I’ll just replicate here what I wrote at the bakery.
This Acl behavior makes a number of improvements from the built-in one. It allows you to have a model act as both an “Aro” and “Aco”. It creates an alias in this format “Model.id”. If parent node is not provided, it’ll create one based on root object. For example, if you create Post.1 as an ACO and you set parentNode to null, it’ll set the parent_id to the root “Post” Aco if it exists. So your tree would look like the following:
Acos ---------- Post |-Post.1 |-Post.2 |-Post.3
Usage Instructions
Follow the following steps to use the Acl behavior.
Step 1
Copy the behavior class into a file named “acl.php” in your /app/models/behaviors folder.
Step 2
Load the behavior in the model you want to use it in.
Examples:
Ex 1: Act as Aco
var $actsAs = array('Acl' => array('Aco'));
Ex 2: Act as Aco
var $actsAs = array('Acl' => 'Aco');
Ex 3: Act as Aro
var $actsAs = array('Acl' => array('Aro'));
Ex 4: Act as Aro and Aco
var $actsAs = array('Acl' => array('Aro', 'Aco'));
Step 3
Create the method parentNode($type) in your model. This will return the parent_id to a method in the Acl behavior.
Here’s an example of a User model passing a group id as it’s parent id only for the ARO:
function parentNode($type) { if ($type == 'Aro') { if (!$this->id) { return null; } $data = $this->read(); if (!$data['User']['group_id']){ return null; } else { return array('model' => 'Group', 'foreign_key' => $data['User']['group_id']); } } else { return false; } }
That’s it!
Download the behavior class here