Follow @endyourif rss Facebook LinkedIn

CakePHP Tutorial

CakePHP is a framework built with PHP based on the Model-View-Controller (MVC) programming methodology. CakePHP offers many diverse features and reusable methods to allow developers to truly perform Rapid Application Development.

CakePHP Tutorial

What is CakePHP?

  • A PHP framework that implements the Model-View-Controller (MVC) programming methodology
  • Simple to implement authentication/authorization with an easy-to-use login system
  • A bakery that makes it easy to scaffold an entire CRUD (Create Read Update Delete) process for any model
  • Flexible form validation
  • Incredible community with hundreds of helpers, components, and templates to make developing with CakePHP fast and easy

CakePHP Examples

Below are a list of CakePHP articles that will provide the essential tools to take you from a beginner to an expert with CakePHP by providing clear and concise demos with practical, real-world examples. Whether you are looking for beginner tutorials or advanced tutorials these examples will provide the essentials to become more proficient with the CakePHP framework.

Using the JsHelper in CakePHP to submit a form with AJAX

The JsHelper in CakePHP 2.x has replaced the AjaxHelper from CakePHP 1.x. I recently tried to implement the JsHelper without very much success; perhaps if I would have read the documentation more closely it would have been quite obvious what my mistake was. So in case you're like me and often skim over long documentation of a helper when you just need one function, in my case: $this->Js->submit() then you can often miss very important information. This article will hopefully help clarify
it.

Using CakePHP to scaffold a new database table

With each new table you create in your database, you will typically need to create a model, controller, and one or more views to get started. CakePHP contains two solutions to get you started creating these files with minimal effort.

Scaffolding allows an application to perform the following four scenarios, known as CRUD: Create, Retrieve, Update, and Delete.

In CakePHP, scaffolding can be done in two different ways. The first way is extremely simple, but doesn’t provide the ability to customize easily. The second way requires a bit of setup time; however, once done, you have full control over customizing any aspect of things.

Using CakePHP with the jQuery Sortable Plugin

It's time to permanently remove all "manual" sorting from the Internet. You know the one I mean where it has the up and down arrows – or even worse, the text box that accepts a numerical order input. By implementing the jQuery Sortable Plugin, you will be able to provide a simple, but effective drag-and-drop ordering solution for just about any type of data!

In a recent article, I described the required HTML and Javascript code need to implement the jQuery Sortable Plugin on a gallery of images. If you haven't already done so, please begin by reading this article because this one will gloss over those features and focus on how to implement this with CakePHP.

Cannot find module (SNMPv2-TC)

When I run PHP via the command line (aka php cli), I often would be spammed with the following error messages:
Cannot find module (SNMPv2-TC)
Cannot find module (SNMPv2-SMI)

Messages like this would repeat for 30 or 40 lines. These errors would not stop my command from executing; however, it was extremely noisy when trying to see the output.

Setting Up CakePHP with IIS

I’ve found myself doing this several times over the past little while as I had to switch computers.  Each time I would struggle with a few of the steps, so I thought I would document them this time and share for future me (or you if you like).

Implementing the Repository Pattern with CakePHP

I must admit, my recent articles are becoming a bit obsessed around the repository pattern.  What can I say, I like it, it’s useful, and it’s not restrictive based on a language or a framework.

I’ve long professed how I dislike convoluted controllers.  CakePHP’s find method almost immediately causes this when used inside a controller.  More importantly, the code inside the find method is extremely unreadable.  This is almost more important than a large controller function!

This is where the repository pattern comes in.  At its most basic example (which some will consider overkill – you know who you are), I still think the repository pattern is clearer.

Here is an example using the regular find approach:



$user = $this->User->find('first', array('conditions' => array('id' => $id)));


Compared to a repository example:


$user = $this->UserRepository->GetById($id);


The code is almost identically; however, in the second example, it’s clear that if I were to “read” the code I am retrieving a user by id opposed to I’m finding the first user with the conditions of id being equal to the variable $id.

So if you are sold, let’s continue with a full suite example…

Changes to Model:find('first') in CakePHP 2.3

A new stable release of CakePHP has just been released a few days ago, version 2.3.  With this many great new changes have come out of it.  You can read the full change log here:
http://bakery.cakephp.org/articles/lorenzo/2013/01/28/cakephp_2_3_0_is_out

One of the things that immediately caught my mind was this great big bolded sentence:

IMPORTANT: Model::find('first') will now return an empty array when no records are found. Make sure you update your tests!

Immediately after reading this I thought major code changes were going to be required; however, luckily my fear was unfounded.  Let me provide an example...

Recent Guest Posts on PHPMaster.com

I've had the pleasure of being a guest writer at a fantastic site called phpmaster.com.  This site is a subsidiary site to one of the most popular technology blogging sites sitepoint.com.

The first article I wrote is an excellent extension of the various CakePHP articles I've written about in the past.  It discusses a variety of ways to improve the speed of CakePHP applications.  The latest article (that was just released a few days ago) discusses creating your very own OAuth server.  Since OAuth2 is still in a draft state, the article is for creating an OAuth1 server.

In case you are not a regular of this site, here is a quick preview of the articles.

CakePHP Global Constants and Functions

If you ever find yourself perusing some of the default code that comes with CakePHP, you might find yourself somewhat curious and confused when you see such functions as <?php e('Hello World');?> or <?pho echo h('<a href="">Hello World</a>');?>.

I know I certainly was and became determined to understand what the heck these were doing.  It quickly became apparent that these were just two of the many built-in extension functions that are part of the CakePHP framework!

CakePHP Extending one View from Another

A new feature in CakePHP 2.1 is the ability to make one view extend another view.  This is a very neat feature; it's actually quite similar to the concept of Jquery templating.  The concept behind it is relatively straight forward.  You define one view that contains common elements that will be updated in another view.  The goal is to avoid duplicating the HTML in a different view.

CakePHP 2.x Login System

Well, since one of my most popular all-time blog posts is Login system with CakePHP in under 10 minutes I think it's time that I update it to version 2.x (currently 2.2 at the time of writing).  The original post was probably written for version 1.2 or 1.1 and there have been several changes made, especially with breaking changes to the AuthenicateComponent.

The beautiful part is the changes are extremely limited.  In fact, only the UsersController requires a few minor changes.

A Short Rant About Coding Conventions

Yesterday's article actually got me a little amped up about coding conventions – Comparing a while loop against a foreach loop of an array – because I never thought I would actually have to do a comparison between a while loop and a foreach loop on an array!  If we go back and revisit the post, I was reviewing a recent CakePHP commit for an optimization on the Hash class.  The code in question is three separate blocks of code that leverage the array_shift function to get the next value in the array with a foreach loop instead.

Are you having CakePHP and NGINX Rewrite Rule Issues?

In a recent blog post – It's LEMP Not LAMP – I discussed about making the switch to using NGINX (pronounced Engine-X).  I had little-to-no issues getting by basic Wordpress blogs up and running.  However, for some reason I couldn't get my older CakePHP sites up and working.

I was racking my brain forever, trying everything I could think of with the rewrite rules – thinking for sure this must be the root of the cause.  In the end I thought it might just be an issue with the version of CakePHP I was using, as it was an older version (1.2.x).  However, I just grabbed a clean copy from CakePHP's Github of 1.2.10 and got it up and running without issues.

I'm of course even more confused at this point, so why am I writing this blog post you ask?  The answer is simple, if you're having issues with getting an old CakePHP site to work on NGINX, try upgrading your CakePHP version.

CakePHP Version Comparison with PHP Version Comparison

I've seen a few recent blog articles comparing the new version of PHP 5.4 to its predecessors and I thought I should get involved with this a bit as well.

To perform this test, I will layout the conditions I have chosen.  I'm trying to keep this as simple as possible.  I currently run a Dell Laptop with Windows 7 on it:

Windows NT 6.1 build 7601 (Unknown Windows version Business Edition Service Pack 1) i586

Because I often do a lot of .NET development recently I have PHP running as a CGI under IIS 7.5.

I then created a very simple .NET application that performs 100 requests of the same web page and tracks the response time.  These lists of response times are sorted and the highest and lowest responses are dropped.  The average is then calculated from this.

Officially published my CakePHP Book

Finally!  It has been a long time in the making, but my book is finally finished and published!  About two years ago, I began the undertaking of writing a book.  At the time it was merely a hobby while I was working on my blog.  Seeing if I could turn the success of my blog articles into a book.

As you may recall a few months ago, I released an e-book.  This e-book was basically my original works written for CakePHP 1.2.  I saw some success with the e-book, so that made me believe that I should seek publishing on my book.  Unfortunately, there isn't much hope for mainstream success with a big publisher like O'Reilly because CakePHP is too small of a niche for them to focus on.

During this time, I focused on upgrading the book to be relevant to CakePHP 1.3.  I even added a special bonus chapter about upgrading from CakePHP 1.2 to 1.3, which I must say was extremely painless; especially if you stick with the standards.

Anyways, I hope you take the opportunity to view my CakePHP book.

Enjoy!

CakePHP 1.2 VS 1.3 VS 2.0 Page Request Times

When I first started using CakePHP a few years ago, we had a lot of complaints about speed.  If you do some Google searches comparing CakePHP to other frameworks, it seems to be near the bottom of the pack.  I previously wrote a few articles on optimizing CakePHP here:


Implementing the following tips certainly helped; however, if there are issues with the core framework response time, no amount of optimization will truley help.  So after reading up on CakePHP 2.0 and it's recent speed improvements, I wanted to do some straight CakePHP comparisons.  Below are 10 load times for CakePHP 1.2, 1.3, and the new 2.0.  These load times are of a brand new install simply loading the default home view, no database connection or any model loading.

AJAX Star Rating Plugin For CakePHP

First off, I didn't write this plugin, I was browsing CakePHP's plugin bakery and it came from there:
http://bakery.cakephp.org/articles/schneimi/2010/08/19/ajax-star-rating-plugin-1

This is an excellent plugin and very easy-to-use.  The above article is extremely detailed and provides excellent step-by-step instructions to set it up and get it running.

In reviewing the comments, like any self-made plugins there were a few issues encountered and ironed out along the way, so if you run into any issues be sure to search the comments.
Enjoy this excellent Star Rating Plugin for your next or current CakePHP site!

CakePHP 2-0 Ajax Pagination WITHOUT The Pages

As I promised in this article, I have created a full CakePHP example of performing AJAX pagination without the pages.  The goal of this article is to display news articles to a user.  As the user scrolls down, we will dynamically load in additional content so they can continue to scroll and read.

One of our challenges is to not load too much or too little content.  For more details on this, please review the theory article.  Let's begin.

CakePHP CSS Enhancements From 1.2 To 1.3

This article does seem a bit late since CakePHP 2.0 is on it's way.  However, I felt it prudent to point out a few things that I'm really happy to see in the new default CSS provided by CakePHP.

On CakePHP's website, you will find an excellent migration guide from 1.2 to 1.3 here:
http://book.cakephp.org/view/1561/Migrating-from-CakePHP-1-2-to-1-3

It describes in great detail the various changes throughout the entire application and there are a lot of them.  But I think it left out some of the most important stuff, the default CSS provided for people who use the bakery to create their websites!

One of the things that irked me in 1.2 was I had to manually update the paginator helper to display what field is currently being sorted on.  Many times I had to ensure my peers were also doing the same thing and a lot of time was wasted checking this and ensuring it was done correctly.

Publishing an e-book on Smashwords

I feel a little bit behind in the times on this one, but I'll work to catch up quickly.  Over the past year or so I've been compiling samples and I put together a book for developing CakePHP websites.  I saught publishing on the book, but unfortunately all of the big name publishers felt that CakePHP is too small of a market.

After being rejected, I wasn't too sure what to do with the book.  So, I left it for a while.  Then, earlier this week through some Google searching I stumbled upon the idea of an e-book.  Previously I've associated e-books with "Get rich quick schemes" as you see a lot of websites selling e-books along those lines.

I started investigating this option a bit more and I found some videos about creating e-books with Adobe Indesign and formatting them for the various readers.  This quickly started sounding like a lot of work!  Instead I searched for other solutions.  That's when I found it: Smashwords.  This is an incredible service.  You upload your Word Document and they automatically convert it for the over 10 e-book options out there!  Not only that, they will sell it and promote it on your behalf.

Interesting CakePHP Bakery Components

I enjoy researching what other people are doing in the CakePHP world and I came across several interesting components at CakePHP's bakery website:

Wizard Component


http://bakery.cakephp.org/articles/jaredhoyt/2010/09/10/wizard-component-1-2-1

This component looks pretty neat and easy-to-use.  You import the component and set a list of steps that the wizard will traverse through.  You then create views for those steps with forms that submit to themselves.  The wizard will then process the form and proceed to the next step for you persisting the data along the way.

Breadcrumbs Component


http://bakery.cakephp.org/articles/rees/2010/08/14/breadcrumbs

This is a component and helper all-in-one.  Inside your controllers, you define the breadcrumbs in each function and you alter your app controller to automatically render the breadcrumbs on each page for you making it a pain-less process to add breadcrumbs to your site!

SMS Text Message Component


http://bakery.cakephp.org/articles/donald_jackson/2010/08/14/component-to-send-sms-text-messages

This is a component that is written specifically for Panaceamoblie that is a helpful service to allow your website to send SMS services.  It works very similar to the EmailComponent.

CakePHP 2.0 Rant Retraction

In yesterday's article, it appears I may have misunderstood something regarding lazy loading.  I incorrectly read it as "loading the data" on-demand oppose to loading the object on-demand.  This actually looks like a great feature, especially after reading this: http://bakery.cakephp.org/articles/Frank/2010/08/10/optimizing-model-loading-with-lazymodel

It appears associated models would automatically be loaded simply because they are related to the model you are querying, even if you are not retrieving data from it.

Thanks for the clarification on lazy loading Jose and I'm actually quite excited to see this change after further research into the situation.  Check out these benchmarks from the above mentioned article:

Before lazy loading


Total Requests made: 100
Total Time elapsed: 6.8480186462402 (seconds)
Requests/Second: 14.603 req/sec
Average request time: 0.068 seconds
Standard deviation of average request time: 0.002
Longest/shortest request: 0.078 sec/0.066 sec
Memory usage: 9.75MB

Post lazy loading


Total Requests made: 100
Total Time elapsed: 4.8957378864288 (seconds)
Requests/Second: 20.426 req/sec
Average request time: 0.049 seconds
Standard deviation of average request time: 0.001
Longest/shortest request: 0.056 sec/0.048 sec
Memory usage: 7.25MB

Almost 6 full requests more per second!  Just in the 100 requests made there is over 2 seconds being gained!  Excellent work community!

CakePHP 2.0 Rant

I was recently visiting the CakePHP bakery and decided to read a little bit about CakePHP 2.0-dev.  I've rather enjoyed CakePHP as a framework since version 1.1 all the way through to version 1.3.  However, after reading some of the "features" for version 2, I have to say, I'm a little disappointed about their focus.

Using the TextHelper with CakePHP

Really, the TextHelper?  Yes, this is probably one of the most overlooked helpers in CakePHP.  Sure we all know about the HTML Helper, Form Helper, JS Helper, etc... but how many of us use the Text Helper?  I've seen so many custom functions for truncating text and adding an ellipsis (...) to the end of it.  How about replacing email addresses with links?  Etc...  No more I say!  Let's begin explorining the Text Helper now.

Modifying the CakePHP Bakery Templates

One of the keys to a successful website is a good user flow.  What defines a good user flow?  At the very core, it requires simple navigation, being able to find what you're looking for, and being able to do it quickly.  CakePHP's bakery let's you quickly create websites that list, add, edit, and delete data.  All you need to do is create a database table and run a few simple bakery commands and this will be done for you.

The basic templates provided are pretty good.  They include links to do all of the above as well as pagination and sortable headers on the table listing page.  I find them a little bland and very "techie".  Most customers don't like this, so let's alter them to suit are needs.

Maintaining the back button with AJAX

Last week I blogged about whether or not you can use too much AJAX on your website.  The short answer was no; with one caveat being that you must not lose the user interaction experience.  In this scenario I'm referring to the back button.  If the user has "felt" like the content changed, they are likely to click the back button to return.  If they do this, it's important for them to "go back" to where they "think" they were and not the last page that was loaded without AJAX!  I've put together a quick example of how to do this.

Optimizing CakePHP Websites

CakePHP offers a lot of functionality to us as developers. The ability to develop websites rapidly provides a trade-off in how quickly the website will load. As we expand our skills, we will learn the techniques that will slow down/speed up performance.



Objectives



  • Apply techniques to speed up CakePHP’s load time

  • Optimize our queries

  • Cache query results


Adding SEO functionality

Two of the biggest things that will improve your search engine rankings are keyword rich website titles and keyword rich links to your content. Today’s lessons will cover both of these topics.


Objectives



  • Improve our search engine rankings

  • Set a title tag

  • Map a specific URL to a custom controller and action

  • Avoid using ids or numbers in our URL


Before I start, I would like to make it clear that this article is and does not intend to be a be-all-to-end-all of the SEO necessities for your website. It is meant to describe some excellent techniques to quickly and easily improve upon CakePHP to make it more SEO friendly.

unbindModel and $this->paginate()

Ugggh what a disaster today was!  On a client's site, we have an older version of CakePHP, pre containable functionality.  Because of this, we have to use unbindModel and bindModel to accomplish the same functionality.

Over the past while, it has not been such a big deal.  However, for some other unknown reason, a search feature wasn't returning back the appropriate associative data.  This had been working for quite some time, then suddenly stopped.  As I mentioned, I'm not exactly sure when and why it stopped working, but it did.

Photobucket, Photos, and You

It seems like photo sharing and social network applications are the in thing right now. Let's take advantage of this. Today I will provide a simple class that will allow you to post photos to a user's Photobucket account in minutes.

Step 1: Visit http://photobucket.com/developer/register to register for an API key

Follow the steps to create a new application on Photobucket. When you have finished, Photobucket will send you an email with your API and Secret key. Keep this email for later use.

Facebook, Photos, and You!

The Facebook Application API is quite extensive and allows you to get and set many different aspects of a user's Facebook information.

Today, we are going to discuss using the Facebook API to create an album, if it doesn't already exist, and add a photo to that album.

Caching Queries in CakePHP

If you haven't noticed already, at times CakePHP can be a little slow loading!  The reason for this is quite simple.  Rapid Application Development.  To allow for RAD, sometimes we must give up something, in this scenario it's a bit of speed when loading.  Don't worry, CakePHP offers some excellent utilities to help with this.

The one I will focus on today is caching our CakePHP query results.  The key to this is, we are caching the results, not the queries themselves.  If you know databases well, you may be thinking, "why do I want to cache queries, doesn't my database server do this already?"  The answer to the question is, yes it does.  However, CakePHP still needs to call the database query and parse your results.  What I'm proposing, will avoid both of those steps and allow you to just retrieve the results.

This process not only avoids excess load on the database, it also reduces PHP's processing time that CakePHP has to do to provide you with such useful arrays.

Custom pagination query in CakePHP

My pet peeve list seems to grow on a regular basis.  One of them is poorly optimized code.  Not only is the code I'm going to discuss poorly optimized, it's from the documentation of CakePHP!

If you search for creating custom pagination in CakePHP, you will find quite a few results, potentially this one.  The one that I would assume the best would be the one from CakePHP itself, but it's not and let me show you why.

3 Flaws to CakePHP's AuthComponent

Good Friday to all.  Over the past several weeks I have been working a lot with the AuthComponent in CakePHP and have learned a couple of lessons that I wanted to share with you all.

The title calls them "flaws", but I suppose this isn't completely accurate, it depends how you look at it.  To me they are flaws because I assumed the AuthComponent worked one way, only to find out different.

A friendly framework reminder

Quite often at work, I find myself reminding my team members to be sure to ALWAYS utilize the framework to it's fullest.  Just because you are unsure how to do something or have never done it before in the framework, does NOT mean that it cannot be done!

I use to have this thinking as well.  I would curse and curse, I've done this a 100 times, why is it so difficult to do with this framework!

Once I calmed down, I would Google it or look around the documentation and pretty quickly discover how to accomplish it using the framework.  9 times out of 10, I found that it was actually extremely easy to implement.  Not only that, 7 or 8 times out of 10, it would actually save me time!  If it didn't the first time, it certainly always saved me a lot more the next time.

Unbind Model Validation in CakePHP

Have you found yourself wanting to remove validation on a specific field in a specific form?  Yes?  Excellent, you found the right place.

If you haven't had the need for this, a great example of where you would want to accomplish this would be in a users edit form.  Normally in CakePHP we would encrypt the password, especially if you are using the AuthComponent, so we wouldn't want the password prefilled on our form.  Instead, we'll make it blank and place a note underneath that says "Only enter a password if you wish to change it".

The above shouldn't be difficult, however, when you go to use the form, you will get some unexpected results.  I keep getting a message saying that I must enter a password, because I had setup validation on that field for the registration process.  Below is a simple solution to this problem.

Login system with CakePHP in under 10 minutes

** If you've found this article through a Google search, visit my CakePHP 2.x Login System for an updated version of this article. **

In today's article, I am going to discuss how simple it is to setup a login system with CakePHP.  As the title says, it should be less than 10 minutes.  In theory if you copy and paste the code below, it should be fully functional in less than 5.

Ready, set, let's bake.

Optimize your CSS and JS with CakePHP in minutes

One of my first articles discussed YSlow.  An excellent Mozilla add-on to help you understand why your web page may be loading slowly.

In that article, I describe the importance of gzip, minify, and grouping your Javascript and CSS code into one file each.

Just recently I was surfing CakePHP's bakery and found a nice add-on to simplify the process and make it super easy.

Importance of using the CakePHP Helpers

Uggghh, I hate to even be writing about this!  I have been spending the past two days cleaning up a project that has been running for over one year.  It was our first ever CakePHP project at our company and we were too lazy to be consistent about using $html->link() when creating our links.

Just recently the client has requested a change for their Facebook application.  We simply need to add a "requirelogin" HTML attribute to every link.

Re-map key/value array data in PHP

I was recently tasked with a situation where I needed to populate about 10 different "Settings" for every user in the current database.

This example is specifically for CakePHP, however, it could easily be used elsewhere.  My goal was the following, I had an array that was key value paired as follows:

array(
 [0] => array(
  'User' => array(
   'id' => 1)
  ),
 [1] => array(
  'User' => array(
   'id' => 2)
  ),
 [2] => array(
  'User' => array(
   'id' => 3)
  ),
 [3] => array(
  'User' => array(
   'id' => 4)
  ),
)

The result I needed was as follows:

array(
 [0] => array(
  'UserSetting' => array(
   'user_id' => 1)
  ),
 [1] => array(
  'UserSetting' => array(
   'user_id' => 2)
  ),
 [2] => array(
  'UserSetting' => array(
   'user_id' => 3)
  ),
 [3] => array(
  'UserSetting' => array(
   'user_id' => 4)
  ),
)

With a few simple lines of code, I was able to quickly and easily achieve this, let me show you how.

When to use element() and when to requestAction()

Several times a week it seems, someone at my office is asking, "Jamie, should I use $this->element() or $this->requestAction()?"

Every time they ask, I ask them back, "What do you need to do?"

There are a few simple ways to determine if using an element is better or a request action is better.

CakePHP Containable Statement Pitfalls

On some of our more recent projects, we have been using the Containable behavior that CakePHP provides.  It works quite nicely, a lot easier than the previous format of having to bind and unbind models on the fly.

The pitfalls began to appear when some of our clients were reporting that some pages are extremely slow.  After a bit of research, it was quite apparent that the root of the cause was attributed to us using the containable feature.

Keeping your CakePHP Controllers Clean

As my office gains more and more experience with CakePHP, we are beginning to learn to build more organized web sites.  Looking back at our first few projects, I'm astonished to see how messy our controllers are!

I know the controllers are the "brain" of MVC because it pieces our data to our views, but that doesn't mean everything should go in there.  Our original controllers would contain all of our logic, all of our data manipulation, all of our custom queries, and some additional data validation.

We are now working very hard to keep our controllers as clean and simple as possible.  My goal is to make every function in our controllers under 20 lines of code.  It might sound ambitious, but I think it is completely feasable.

Drag and drop category management with CakePHP

Today's article is going to walk you through creating a slick drag and drop with AJAX category management system.

CakePHP offers a really nice built-in tree management.  In fact, at a bare minimum you simply need to create a table with 2 extra columns, tell your model to act like a "tree" and rather than doing a find('all') you do a generatetreelist() or a find('threaded') and CakePHP takes care of the rest.

After doing a quick test, I was quite impressed with what CakePHP did for me, but I was not satisified.  I wanted to create a really slick category management system that I can re-use and show off.  Well, in this tutorial I go about 90% of the way.  The only thing I didn't have time to finish was, rather than redrawing my tree through AJAX, use DHTML and dynamically update my tree after dragging and dropping.  Don't worry, I plan to finish this with a part two soon.

How to add comments with AJAX in CakePHP

In today's article we are going to create a very basic blog that allows people to create a post and posts comments on that post via AJAX.  We are going to keep it extremely basic and just focus on that actual AJAX functionality.

Ready? Let's begin.  We are going to start by creating two database tables: posts and posts_comments.  Below is a sample create statement for the posts table:

How to advance our CMS in CakePHP

At the end of part one, we had a working CMS.  Well, at least it was saving files and they could be displayed to the public.  In today's article, we are going to further advance our CMS.  We will cover the following items:


  1. fckEditor

  2. Revisions


How to create a CMS with CakePHP

I really enjoying writing code and I find that snippets just don't always cut it for me.  So in today's article, I am going to describe the process of creating a CMS (Content Management System) with CakePHP.

This will be a two part article, in part one we will focus on getting the basics working.  The basics will include ability to add, edit, and delete static content pages.

Part two will advance on our basis and allow us to create drafts and revert back to previous versions.

AJAX Select box in CakePHP

When I created my first personal CakePHP web site, this was something that had me quite frustrated.  I struggled and struggled to figure out and understand how to do a simple "if I change this select box, how can I populate another one".

I had previously done this a million times in other languages with a simple "onchange()" function that would do my AJAX and populate my other select box.

To solve this problem, I checked CakePHP's web site and did not find anything useful.  Don't forget this was almost a year ago, I find the web site has come a long way now.  Because I couldn't find a could example, I did the next best thing, I dove write into the form helper and ajax helper.  Shortly after, I found enough information to start my trial and error process.

Excellent, now we are getting some where.  Now that we know this, let's create our two select boxes and make our second one populate through AJAX.

How to setup a route in CakePHP

If you are like me and are creating personal web sites, one of the best ways to gain traffic to your site is through SEO.  I won't go into detail here as I want to focus on how to setup a route in CakePHP, but having SEO friendly URLs will go a long way in helping.

First let's define what a "route" is.  In CakePHP it allows you to add a different path to access a specific controller and/or function in that controller.

For example, let's say I want to create a CMS.  I might create a controller called "StaticContent" and then place a function for each page a client would like to create.  I'm pretty sure I would start getting a lot of calls saying, "Jamie, why is my URL http://www.myaddress.com/StaticContent/myCustomPage?"  So to avoid those calls, we can use a route to make it more accessible and SEO friendly.

StringExtractComponent for CakePHP

Hi folks, I have just finished creating my first CakePHP component and I wanted to share it with the community.  After I finish writing this article, I will be submitting it to CakePHP for inclusion.

The component is called StringExtractComponent.  As you may guess, it extracts content from a piece of content.  I have created this component to mimic the STREXTRACT function in Microsoft Visual FoxPro.  I have come to fall in love with this function because it makes retrieving data from a string with a start and end delimiter.

To help you understand how it is used, I read the contents of one of my articles into a string.  I then proceed to extract a specific section that is contained within the code syntaxes that exist in the article.

Why Frameworks Are Better

Are you a person who dislikes frameworks?  Or are you a person who loves frameworks?  Or are you even a person who isn't quite sure what a framework is?  The following article will discuss the pros and cons of frameworks and the common downfalls that people fall into.

I'm not sure if it's only people I meet or a world-wide thing, but it seems people do not like to use frameworks (at least at first).  At my work, we use them on every new project.  So, when a new hot shot developer joins our team, we inevitable get to have the battle of "Ugghh, I don't want to use a framework I want to code my way and only my way".

If this is your typical response to frameworks, I suggest you continue to read and let me enlighten you on why we live and die by our frameworks.

CakePHP Book

If you are looking for a CakePHP book, this was the first book I ever wrote. It is self published and I've done my best for formatting the code examples. The book is available in PDF format as well as paperback.

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP