Archive for the ‘PHP’ Category


CakePHP: Containable Behavior is Your Friend

Thursday, February 18th, 2010

When it comes to optimizing your CakePHP queries, you need to abandon Recursive and adopt Containable.

In the example below I have the following models:

  • Patient
  • Specimen
  • Result
  • ResultType

The associations in the model are:

  • Result
    • belongsTo
      • ResultType
        • hasMany
          • Result
      • Patient
        • hasMany
          • Result
          • Specimen
      • Specimen
        • belongsTo
          • Patient
        • hasMany
          • Result

(more…)

Simple Security in CakePHP

Wednesday, July 22nd, 2009

When I started to dig in to investigate using the Security Component of CakePHP, I was a bit daunted. It took me quite a while to get my head around ACL after all. Then I found this article. Here’s the crux:

The Security component will create a hash based on the form fields produced by our Form Helper. If someone tampers with the form fields (by adding or removing or changing any field), the hash is not going to match with the expected one and the add() action will fail.

Yep, it’s that simple.

Really? It just can’t be that easy, can it? Yes. It can. I simply added the Security Component to my controller like so:

var $components = array('Security');

Sure enough, when I reloaded a page with a form in my browser, this hidden field was there:

<input id="TokenFields1483167134" name="data[_Token][fields]" type="hidden" value="f513aebc448fabe42c7feedf31d43fa5bd71ec79%3An%3A0%3A%7B%7D" />

I installed a Firefox Add-on that allowed me to tamper with the POST data, and when I submitted the form, it failed, or in CakePHP terms, it was “Blackholed.” Awesome.

This isn’t going to protect me from all attacks, but it certainly is a good, easy start to implementing security in my application.

Roll Your Own CakePHP Components

Friday, May 22nd, 2009

As someone who is not formally trained as a programmer, I often understand concepts long before actually putting them into practice. Don’t Repeat Yourself (DRY) seems simple enough. Of course I don’t want to repeat myself while programming. Who wants to dig through lines of code to find a litte snippet of logic you once wrote? Still, when you’re pressed for time, sometimes you just have to Get Things Done (GTD). So best practices go through the window and you hammer out some spaghetti code so you can move on.

It’s only recently, since I’ve slowed down to finally understand how to write CakePHP Components, that I’ve realized that DRY enhances GTD. Now that I’ve got it all straight in my head, I’m a component evangelist.

At this point I’m going to assume that you’re familiar with MCV architecture and its benefits. Once in a while there’s a bit of logic that you find yourself coding into a controller that you realize you’re going to want to use in other controllers. It’s not specific to the model. That’s where components come in. They’re bits of logic that can be used by more than one controller. Let’s look at a simple one that converts mm/dd/yyyy dates to a Unix timestamp.

<?php
 
class DateComponent extends Object {
 
	function mkTimestamp($sentdate, $senttime){
 
		$thedate = explode('/', $sentdate);
 
		if(!empty($senttime)){
 
			$thetime = explode(':', $senttime);
			$newdate = mktime($thetime[0],$thetime[1],0,$thedate[0],$thedate[1],$thedate[2]);
 
		} else {
 
			$newdate = mktime(0,0,0,$thedate[0],$thedate[1],$thedate[2]);
 
		}
 
		return $newdate;
 
	}
 
}
?>

The function itself is not all that complicated. The thing is that I’m going to want to use this where ever I need to convert dates. Since the component is called “Date”, it’s named with the CakePHP convention for components: DateComponent. The file is called date.php and is saved in app/controllers/components.

Now we have to tell our controller(s) to use it. I’m using it across several controllers, so I’m adding it to app/app_controller.php by adding it to the $components var: var $components = array('Date');

Now I can access it in any controller like so: $tmsmp = $this->Date->mkTimestamp($thedate, $thetime);

The whole point is that components don’t have to be complex, they’re just code you want to reuse that doesn’t necessary apply to one model. They will save you time and clean up your controllers.

CakePHP Console ACL Help File

Sunday, March 22nd, 2009

Every now and then I want to view my help files in pretty, formatted HTML instead of plain text in a text editor or terminal window. Right now I’m working on setting up some Access Control Lists (ACL) in the CakePHP Console. ACL is a powerful, yet sometimes hard-to-grasp concept. I always figure that if I want a resource like this, there has to be someone else out there who does, so for your reference and mine, here it is. (By the way, to get to this from the console, simply type cake acl help.)

Usage: cake acl <command> <arg1> <arg2>...
———————————————–
Commands:

create aro|aco <parent> <node>
Creates a new ACL object <node> under the parent specified by <parent>, an id/alias.
The <parent> and <node> references can be in one of the following formats:

  • – <model>.<id> – The node will be bound to a specific record of the given model
  • - <alias> – The node will be given a string alias (or path, in the case of <parent>),

i.e. ‘John’.  When used with <parent>, this takes the form of an alias path,
i.e. <group>/<subgroup>/<parent>.
To add a node at the root level, enter ‘root’ or ‘/’ as the <parent> parameter.

delete aro|aco <node>
Deletes the ACL object with the given <node> reference (see ‘create’ for info on node references).

setParent aro|aco <node> <parent>
Moves the ACL object specified by <node> beneath the parent ACL object specified by <parent>.
To identify the node and parent, use the row id.

getPath aro|aco <node>
Returns the path to the ACL object specified by <node>. This command is useful in determining the inhertiance of permissions for a certain object in the tree.
For more detailed parameter usage info, see help for the ‘create’ command.

check <aro_id> <aco_id> [<aco_action>] or all
Use this command to check ACL permissions.
For more detailed parameter usage info, see help for the ‘create’ command.

grant <aro_id> <aco_id> [<aco_action>] or all
Use this command to grant ACL permissions. Once executed, the ARO specified (and its children, if any) will have ALLOW access to the specified ACO action (and the ACO’s children, if any). For more detailed parameter usage info, see help for the ‘create’ command.

deny <aro_id> <aco_id> [<aco_action>]or all
Use this command to deny ACL permissions. Once executed, the ARO specified (and its children, if any) will have DENY access to the specified ACO action (and the ACO’s children, if any). For more detailed parameter usage info, see help for the ‘create’ command.

inherit <aro_id> <aco_id> [<aco_action>]or all
Use this command to force a child ARO object to inherit its permissions settings from its parent. For more detailed parameter usage info, see help for the ‘create’ command.

view aro|aco [<node>]
The view command will return the ARO or ACO tree. The optional id/alias parameter allows you to return only a portion of the requested tree. For more detailed parameter usage info, see help for the ‘create’ command.

initdb
Uses this command : cake schema run create DbAcl

help [<command>]
Displays this help message, or a message on a specific command.

The ‘create’ help file

Usage: cake acl <command> <arg1> <arg2>…
———————————————–

  • Commands:
    • create aro|aco <parent> <node>
      • Creates a new ACL object <node> under the parent specified by <parent>, an id/alias. The <parent> and <node> references can be in one of the following formats:
        • - <model>.<id> – The node will be bound to a specific record of the given model
        • - <alias> – The node will be given a string alias (or path, in the case of <parent>), i.e. ‘John’.  When used with <parent>, this takes the form of an alias path, i.e. <group>/<subgroup>/<parent>. To add a node at the root level, enter ‘root’ or ‘/’ as the <parent> parameter.

Use Functions from Other Controllers While Maintaining MVC Architecture in CakePHP

Wednesday, December 10th, 2008

UPDATE (7/22/2009)

requestionAction may not be the best solution. Read this.

At my day job, I’m working on an application to keep track of specimens for our lab. A specimen is sent to the lab, then divided into aliquots which are put into boxes and stored in freezers. The previous sentence ought to give you some idea of the architecture of the database, which in turn drives the Model for my application.

To take a step back for a second, I’m developing the application using the CakePHP framework which uses MVC architecture.

As you may have guessed I have specimen, aliquot, boxes and freezers tables. In turn then, I have Specimen, Aliquot, Box and Freezer Models.

The trick here is that I want to alert users when there are aliquots in the system that have not yet been assigned to boxes. It’s a simple query:

SELECT COUNT(aliquot.id)
FROM aliquots
WHERE aliquots.box_id IS NULL

The problem is that I want the number of unstored aliquots to be displayed on every page in the left column as a persistent reminder that there are are aliquots that need to be put away. I want to do that in a way that maintains the MVC architecture and doesn’t violate the DRY philosophy.

Since the query is run on the aliquots table and each view is generally specific to it’s own model, I either have to run a recursive query to access data across models–which adds overhead–or implement the solution below which lightens the load a bit and is a more elegant bit of code. (Tip of the hat to Jon Bennet for offering the solution.)

The solution involves CakePHP’s requestAction().

I can define the method in my aliquots controller and call it from anywhere. So if aliquots_controller.php has a method that retrieves the data from the model (in this case called ‘unstored’) I can simply put the following code into my layout:

$unstored = $this-&gt;requestAction('aliquots/unstored');
if(!empty($unstored)) {
echo $html-&gt;link('<strong>' . $unstored['unstored'] . ' aliquots have not been stored.</strong>', '/aliquots/store');
}

I only have to define the method once to use it throughout my application. Problem solved.

Getting Blueprint CSS & JavaScript Libraries Into Your CakePHP Layout

Wednesday, November 26th, 2008

Updated 12/3/2008

The other day I wrote about getting the Blueprint CSS framework into your Wordpress theme. If you’re developing in CakePHP, it’s even easier to link multiple style sheets and JavaScript libraries to your layout file.

<?php

$css = array('blueprint/screen', 'blueprint/ie', 'style');
$jslibraries = array('prototype', 'scriptaculous', 'jquery');

echo $html->css('blueprint/print', 'stylesheet', 'media="print"');

echo $html->css($css, 'stylesheet', 'media=”screen, projection”');
echo $javascript->link($jslibraries);

?>

Let’s take these one at a time.

$css = array('blueprint/screen', 'blueprint/ie', 'style');

CakePHP’s html helper will load any css file you specify. First, make sure the css files are in app/webroot/css. Then put any css files you want to link to your layout in an array like I have above. You might have noticed that I didn’t include print in my array. That’s because we want to add an media=”print” as a separate attribute that the other style sheets won’t have.

Once they’re loaded into your array, simply put echo $html->css($css); in the head of your layout. The output will be:
<link rel="stylesheet" type="text/css" href="/app/webroot/css/blueprint/screen.css" />
<link rel="stylesheet" type="text/css" href="/app/webroot/css/blueprint/ie.css" />
<link rel="stylesheet" type="text/css" href="/app/webroot/css/style.css" />

We still haven’t linked our print style sheet. Make sure you link the print style sheet above the others so they override it. We can add media="print" by putting this into our layout head:

echo $html->css('blueprint/print', 'stylesheet', 'media="print"');

So now:

$css = array('blueprint/screen', 'blueprint/ie', 'style');
echo $html->css('blueprint/print', 'stylesheet', 'media="print"');
echo $html->css($css, 'stylesheet', 'media=”screen, projection”');

Results in:

<link rel="stylesheet" type="text/css" href="/cvp-msi/https/app/webroot/css/blueprint/print.css" media="print" />
<link rel="stylesheet" type="text/css" href="/cvp-msi/https/app/webroot/css/blueprint/screen.css" media="screen, projection" />
<link rel="stylesheet" type="text/css" href="/cvp-msi/https/app/webroot/css/blueprint/ie.css" media="screen, projection" />
<link rel="stylesheet" type="text/css" href="/cvp-msi/https/app/webroot/css/style.css" media="screen, projection" />

Two things to note. In $html->css($path, $attributes), the first argument is the path from app/webroot/css. The second argument is html attributes.

Linking JavaScript libraries is very similar.

$jslibraries = array('prototype', 'scriptaculous', 'jquery');

This will link to prototype.js, scriptaculous.js and jquery.js respectively as long as there in app/webroot/js.

Put echo $javascript->link($jslibraries); into the head of your layout and you’re done. You have all three JavaScript libraries at your disposal.

Other good resources:

Incorporating Blueprint CSS Into Your New Wordpress Theme

Sunday, November 23rd, 2008

If you’re familiar with the Blueprint CSS framework, you already know it can make your life a lot easier. So how do you get it into your Wordpress theme? Luckily, Wordpress is designed to make your life easier too.

I’m assuming your know the basics of Wordpress Theme Development. That is, at the very least you need:

  • header.php
  • footer.php
  • index.php
  • style.css

Put those files in a folder named after your theme. And put that folder in /wordpressroot/wp-content/themes/.

Once you’ve gotten that far, download the Blueprint CSS Framework and drop the “blueprint” folder from that download into your theme’s directory.

Finally, to include the new CSS files into your theme, just add this code to your header:

<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/blueprint/screen.css" type="text/css" media="screen, projection">
<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/blueprint/print.css" type="text/css" media="print">
<!--[if IE]>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/blueprint/ie.css" type="text/css" media="screen, projection">
<![endif]-->
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />

Pay attention to the order. You want to make sure that href="<?php bloginfo('stylesheet_url'); ?>" appears last in the list of style sheets. That’s your style.css where you can tailor the CSS for your specific design.

That’s it.

And We’re Back!

Monday, September 22nd, 2008

I have been so incredibly busy the last few months that aside for 140 character Twitter updates, I haven’t been able to keep this blog updated with my exploits.

If you are still paying attention, I was complaining about ACL. After several attempts, I gave up using the built-in ACL component in CakePHP and just decided to keep things simple, use the Auth component with role-based access control. Problem solved.

The development of the application has progressed smoothly since getting over that hurdle.

In the meantime, I’ve been setting up my own virtual server for hosting websites for my freelance clients. That has been a learning experience in itself. I’ll post more about that as I formally launch that service.

I’m also way behind on podcasts for the Minneapoliscast podcast. I hope to resume that at a modest pace this fall.

More later as all of my respective projects get updates including SVN info on my CakePHP app.

Wow. ACL is Hard

Friday, June 20th, 2008

That is Access Control Lists. I’ve been developing with CakePHP this spring and summer and it was all going very well until I actually needed to control access to the application. It’s not even that CakePHP falls short here. There are apparently tons of built-in tools for managing access. They’re just poorly documented and the community is relatively new so no one has built a complete plug in. If you’re looking for a solution like I was, I’m afraid I’m not going to give you the best answer here. I did find something that works, so read on. Especially if you’re learning ACL or Modified Preorder Tree Traversal Algorithm (MPTTA) for the first time.

Disclosure: I’m not formally trained as a programmer/developer. Everything I’ve learned, I’ve taught myself. So there are definitely some silos in my knowledge as I’ve learned things on the basis of necessity. I have, however, been developing in PHP for over six years. So it’s not all that bad.

So the learning curve for implementing ACL has been relatively steep for me. First, I had to get my head around the concept. The big picture is easy. What we’re after is a tree of access with ‘admin’ at the root and everything else branching off from that with diminishing access. That’s not hard to conceptualize. What is hard is putting that into practice.

I messed around with this for a long time before stumbling upon this tutorial about the Modified Preorder Tree Traversal Algorithm. Stop now. Read it. Come back.

Now you should understand the concepts that drive CakePHP’s ACL. Unfortunately here is also where we depart from using CakePHP’s tools. At least until a decent plug-in comes along that allows you to manage Access Request Objects (ARO) and Access Control Objects (ACO) via a good, web-based interface.

After many attempts with various solutions that are currently avaliable, I finally settled on Authake.

Pros:

  • Works in CakePHP 1.2
  • User, ARO & ACO adminstration is a snap
  • Access control works immediately without modifying anything you’ve built in your app.

Cons:

  • Installation requires you replace the entire CakePHP engine with Authake’s modified version. This will make upgrading CakePHP a lot harder.
  • The developer has abandoned it in favor of developing in RoR. No hope for future versions unless the community continues development. Personally, I’d prefer a plug-in like Jeff Loiselle’s ACL Management Plugin that I could just drop right into app/plugins without replacing the entire installation. (The issue I have with Jeff’s are all listed on his “Known Bugs” list. Namely, “does not show inherited permissions, does not show full path in finder & does not have crud fields”. Unfortunately, those are three very major elements of managing ACL.)

If you are reading this in the not so distant future and someone had developed a plugin that has an admin area like Authake’s but drops into app/plugins like Jeff’s plugin, please, please let me know.

My Private Summer of Coding

Tuesday, May 13th, 2008

A couple of weeks ago I met with Garrick VanBuren to talk about cullect.com. I came away from the lunch excited about two things: Trying out some of the features in cullect that I hadn’t quite understood before and giving Ruby on Rails another shot.

I went to lunch with Garrick to offer him some feedback about why I hadn’t adopted cullect yet. (I’ve had an account for about 7 months.) A few colleagues were raving about it. I knew I had to be missing something. I was.

While I think cullect has a way to go before widespread adoption (it runs a little slow on my PowerBook), I see what everyone else likes about it and more importantly, I see lots of potential. So, nice work Garrick. I drank the Kool-Aid. I now curate a small batch of feeds about music and “recommend” posts so the best rise to the top in my “Important” list. This way I can also repurpose those same articles to Minneapoliscast. In other words, I can repurpose content so that relevant reading is included with what I publish. It’s fun and it’s cool.

I’m not even going to talk about how you can pay cullect so that part of your monthly subscription goes to publishers you read. I can’t even tell you how cool I think that is.

What I really wanted to write about is how I came away from our conversation inspired to try Ruby on Rails. I’ve been toying with RoR for about a year now. As I started working my way through Agile Web Development on Rails last year, the realization gradually dawned on me that I was going to have to sit down and learn Ruby. So I bought a pdf version of Programming Ruby, but I didn’t really get very far before other duties called. I just didn’t have time to learn a new language.

After talking with Garrick I was determined to give it another shot. Then I thought, there has to be a Rails-like set of tools for PHP–a language I’ve been working in for years. That thought and a quick Google search led me to CakePHP.

Two weeks later and I’m near completion of the first module to manage clinic and lab data here at work. Once I got my head wrapped around MVC and the built-in helpers in CakePHP, the development got faster and faster. (Disclosure: The database was already fully envisioned and built beforehand. An important first step.) I can’t tell you how gratifying it is to quickly code something in a few lines, test it and have it work. I have a whole summer of coding ahead of me. I’m very excited to deploy this application by fall.

On a final note, I was feeling a little cocky, so I coded my first Wordpress plugin yesterday too. Again, easy. It’s not quite ready for public release yet but with a little tweaking, I might just release it. Basically it just pulls in PodPress data and lists the ten most popular podcasts on Minneapoliscast.

I was a little worried that with our research slowing down over the summer I was going to be bored. Now I’m really looking forward to the coming months. Fun stuff.