Using CakePHP “Parts” in Other Applications
So, you have some third party PHP based web application, and you want to somehow “link” it with your CakePHP site. Wouldn’t it be great if this other application could share some things with your Cake site, like use your existing security components to check if the current user is authorized to use this third party application, or have this third party application retrieve session information for the current user?
I had to do just this in one of my current projects. I used the kfm file manager, and wanted to integrate it into a CakePHP web site as seemlessly as possible. I was mainly concerned with access and authorization as I wanted to use the same components/controllers that my CakePHP based site used to control access. This way, all security management is done from a single place, and everything is nicely integrated.
I had already decided to use the KFM ajax file manager, as you can use it stand alone, or have it integrated with TinyMCE or FCKeditor. It has themes, and it has a great ability to add custom calls when starting it up to integrate it into other CMS’s. Because KFM was all setup to be nicely integrated, I just had to figure out how. While the rest of this post will be KFM specific, the CakePHP integration code should work on any application that has similar integration capabilities as KFM.
At first, I just wanted access to CakePHP’s sessions, so that I could query the current users session, and then decide if the current user had enough permissions to access KFM or not. While this was the road that I initially wanted to go down, I quickly realized that I would be duplicating much of the code that was already written in my CakePHP site – mainly all the security calls.
I would have to query for the current users permissions, and then map them out to make sure that the current user had the required permissions to access the KFM application. I already had a component that does this in my CakePHP site. All the controllers and views in the cake application just need to query a single method in this component to check if the current user has the required permissions or not. Wouldn’t it be great to just re-use this same component – to just be able to call it from KFM?
Well, it turns out, that with a little bit of work (not too much work – so don’t be scared), you can do this!
Let’s dive in.
KFM has a config.php in it’s api directory, where you can write custom code which will be executed when KFM starts. Basically, if this script returns true, then KFM launches. So all that is needed is to load CakePHP up in a way that doesn’t “take over” KFM, query the needed CakePHP components/controllers that control authorization in your CakePHP application, and return true if the user has access, or exit and redirect with an error message if the user doesn’t. So it makes sense that this is where our CakePHP integration will take place.
My KFM\api\config.php file looks like this:
Configure::write('debug', 0);
App::import('Component', 'SiteAuth');
App::import('Controller', 'AppController');
App::import('Helper', 'Session');
$controller = new AppController();
$siteAuth = new SiteAuthComponent();
$siteAuth->Session = new SessionHelper();
if ( $siteAuth->verifySession() && $siteAuth->authorize('manage/files', 'edit') ) {
return true;
} else {
$controller->redirect("/bounce/display/AccessDenied/FileManager");
exit;
}
Ok, there it is, let’s step through it so that we all understand everything.
This first line is the trickiest:
Where is this cakephp.php file, and what’s in it?
Well, this is a copy of CakePHP’s index.php that is in the webroot folder. By default this is in the app\webroot folder in the CakePHP distribution, but use the one that is in your webroot folder – the one that is configured to work for your site. Make a copy of it, and rename it something else. I chose cakephp.php, you can call it anything you like.
At the end of the file, you will see a section that has the following code in it:
you will want to change it to this:
return;
} else {
//$Dispatcher = new Dispatcher();
//$Dispatcher->dispatch($url);
}
//if (Configure::read() > 0) {
//echo "<!-- " . round(getMicrotime() - $TIME_START, 4) . "s -->";
//}
I left the lines commented so you could easily see the changes that we made, but you could just delete everything from “else” onwards – just make sure that you leave the last ‘?>’ ending PHP line at the end of the file.
The first commented section (in the else{} block), is because we don’t want CakePHP’s dispatcher, we just want enough of CakePHP to load so that we can use most if it’s features without cake ‘taking over’ and trying to match the URL’s to controllers and actions.
The second commented section is the ‘if’ block. This is the block of code that prints out the page generation time – and we don’t want that present in KFM in any way. We don’t want CakePHP to echo anything out that will interfere with the HTML that is generated by KFM.
Once these changes are done, simply including this file in KFM’s config.php will load enough of Cake so that we can “tap” into it and use it’s features.
The next line is:
This is Cake’s configure array, and we are making sure that there is no Cake debugging on, so that Cake will not “echo” anything out to the browser – we just want KFM to output HTML, not Cake in this case.
The next three lines is where the magic starts happening:
App::import('Controller', 'AppController');
App::import('Helper', 'Session');
These are straight-up CakePHP import calls. The first App::import (the SiteAuth Component), is the custom component that I was talking about. This is not a CakePHP bundled component, but you may have one that is similar in your CakePHP application.
This component handles all my authorization checks for the entire Cake app, and this is the component that I want to use.
I then load up the AppController, and Session Helper that come with CakePHP.
The next lines simply instatiate instances of the objects that we imported above:
$siteAuth = new SiteAuthComponent();
$siteAuth->Session = new SessionHelper();
At this point, I have access to CakePHP’s sessions, and all the methods/properties that come with the SessionHelper(), along with all of the methods/properties that are available in my AppController(). In addition, I have access to my custom component (SiteAuth). Basically, I have enough of cake loaded to do almost anything I want.
Notice here that I instantiate the SessionHelper() in my siteAuth component’s Session property. For other people, you can simply instantiate it to something like $session.
You may need to import other objects and instantiate them, the import thing here is that we have access to all of CakePHP. We can load up models, components, controllers, Helpers…pretty much anything, and start writing PHP in the normal CakePHP way.
Once I have all of the needed CakePHP ‘parts’ loaded, I make the calls I need:
return true;
} else {
$controller->redirect("/bounce/display/AccessDenied/FileManager");
exit;
}
This again is custom to my application, but basically, you will want to verify that the session is valid, and make authorization calls to whichever component/controller you use to authorize your users. if the test passes, return true, otherwise exit and redirect the user somewhere else (access denied).
I have a simple “bounce” controller that basically centralizes all my Flash messages in my CakePHP application. My controller->redirect call in the end redirects the user to this bounce controller that simply set’s the appropriate flash message for an “Access Denied” error, and uses the argument “FileManager” to tell the user that he/she was Denied Access to the File Manager section of the application.
My ‘bounce’ controller also takes care of all the needed logic to redirect the user to the last page he/she had access to, or the site’s root, so if you don’t already have anything like this setup, you may just want to set a Flash ( $session->setFlash(); ) message up in here manually and redirect the user ($controller->redirect(); ) to the site root (or whatever makes sense to you).
Anyways, I hope that this made some sense, and showed you how to load up Cake in a third party app that allows integration, and how to import the needed classes/objects to tap into CakePHP’s power and features, and re-use your CakePHP controllers and components in an interesting way so that you are not rewriting things from scratch.
Let me know if this helped any of you…

Very handy trick, thanks
Great tutorial, worked like a charm for me.
Thanks for the helpful trick. Had to alter it a bit to work with CakePHP 1.1 like so:
change:
App::import(‘Component’, ‘SiteAuth’);
App::import(‘Controller’, ‘AppController’);
App::import(‘Helper’, ‘Session’);
$siteAuth->Session = new SessionHelper();
to:
loadComponent( ‘SiteAuth’ );
loadController( ‘AppController’ );
loadComponent( ‘Session’ );
$siteAuth->Session = new SessionComponent();
Thought this might help some one else out that is stuck in the CakePHP 1.1 era
Just tried this trick using CakePHP 1.2.5 and KFM 1.4.3 and it failed. KFM will fail trying to load Cake’s classes dynamically from its own classes folder. Here is the error message:
Warning: require_once(/home/kry/public_html/app/webroot/kfm/classes/Set.php) [function.require-once]: failed to open stream: No such file or directory in /home/kry/public_html/2009/app/webroot/kfm/initialise.php on line 17
I haven’t found the “right” solution yet but it looks like a conflict with the __autoload function between the two applications.
Thanks Malcolm for the CakePHP 1.1 update.
@kyle, yes, I can confirm that this is happening to me also…and I also noticed that KFM 1.4.3 has other issues, more issues that it’s previous version, so I rolled back.
I will be running more tests to see if I can get things figured out, but I am also working on integrating tinybrowser and cake, as I really like the minimalist approach that tinybrowser is taking, and it’s progressing nicely.
Thanks a lot for that! I’ve been trying to access the cake session from the webroot for a while but couldn’t find out how. It really helped me!
I’ve managed to find a workaround to get this method to work with KFM 1.4.3
In the kfm/api/config.php I needed to change
to
at the top.
Then in the kfm/initialise.php on line 17 i added the line
giving the function:
function __autoload($class_name) {
if(file_exists(KFM_BASE_PATH . 'classes/' . $class_name . '.php'))
require_once KFM_BASE_PATH . 'classes/' . $class_name . '.php';
}
}
It looks like KFM is trying to include files for CakePHP classes, this just checks if the class file exists in KFM before including it.
Hope this helps someone.
Thanks for that reply danabel – that’s great, and I am sure that it will help.
PS – I fixed a couple of typos you had – but other then that, I haven’t changed anything else.
I also noticed that KFM was now trying to include CAKEPHP files – it didn’t do that before…good idea on the wrapper for __autoload().
thanks again.
yoo.. thank you for this post )
Sorry for choosing this to leave a offer for all about 505 natural prilosec alternatives
maximum dose for prozac prozac side effects caffeine prozac purple green xenical new zealand i have xenical xenical hoffman la roche switzerland prilosec as house brand prozac drug interactions contraindications
Sorry for choosing this to leave a offer for all about 993 dbol nolvadex dosage
clinical pharmacology of lasix blood transfusion steps lasix lasix for sale nolvadex dosage for bodybuilder nolvadex extreme gaspari nolvadex no prescription mexico directions for taking zithromax how long before zithromax expires zithromax 250 mg effexor and generic comparison marijuana effexor xr ativan interractions wellbutrin plus effexor accutane vitamin a accutane centre mesothelioma law information accutane long bones