Grow your CSS skills. Land your dream job.

Getting Started with CakePHP: An Event Manager

Published by Guest Author

The following is a guest post by r0mk1n. I was able to easily follow along and have the demo app up and running on my machine in just a few minutes. It's pretty cool how easy it has become to quickly build powerful web applications.

CakePHP is a free, open-source, rapid development framework for PHP. It’s a foundational structure for programmers to create web applications and enables you to work in a structured and rapid manner–without loss of flexibility. In this tutorial we are going to be exploring the benefits of using CakePHP and provide an example project, an Event Manager style application, to help get you started.

CakePHP takes the monotony out of web development. We provide you with all the tools you need to get started coding what you really need to get done: the logic specific to your application. Instead of reinventing the wheel every time you sit down to a new project, check out a copy of CakePHP and get started with the real guts of your application. CakePHP has an active developer team and community, bringing great value to the project. In addition to keeping you from wheel-reinventing, using CakePHP means your application’s core is well tested and is being constantly improved.

Here’s a quick list of features you’ll enjoy when using CakePHP:

  • Active, friendly community
  • Flexible licensing
  • Compatible with versions 4 and 5 of PHP
  • Integrated CRUD for database interaction
  • Application scaffolding
  • Code generation
  • MVC (Model, View, Controller) architecture
  • Request dispatcher with clean, custom URLs and routes
  • Built-in validation
  • Fast and flexible templating (PHP syntax, with helpers)
  • View Helpers for AJAX, JavaScript, HTML Forms and more
  • Email, Cookie, Security, Session, and Request Handling Components
  • Flexible ACL (Access Control List)
  • Data Sanitization
  • Flexible Caching
  • Localization
  • Works from any web site directory, with little to no Apache configuration involved

Idea

The main idea of our tutorial is to create a simple Events Manager using CakePHP. Our project will:

  • Create / Update / Deleting events with or without attached location (This is often called a CRUD style application)
  • Create / Update / Delete locations
  • Show all events in a list view or calendar view
  • Provide an RSS feed for all events

Our project also includes these advanced technical concepts:

  • Using 3rd party components (Swift Mailer)
  • AJAX functionality (jQuery + CakePHP)
  • Custom helpers
  • Custom Users access control (based on user role)
  • Creating Backend

There are the things you will need for this project to run:

  1. Apache web server with enabled mod_rewrite
  2. PHP version 5 or higher
  3. MySQL
  4. SVN client

Project installation

If you wish to work locally, using a tool like MAMP/LAMP/WAMP can be a great way to go. You can make a local development domain and work from there.

Where ever you choose to work, create a folder in your server's root directory. You may be working locally with a tool like MAMP/WAMP/LAMP, or be working on online developent server. You may name it whatever you like. Navigate to this folder with your shell access and run this command:

svn checkout http://cakephp-tricks.googlecode.com/svn/trunk/ cakephp-tricks-read-only

Creating the Database and SQL Structure

Now you need to create a new database in MySQL. Do that however your web host provides, or locally, you can use a tool like Sequel Pro.

You can name it whatever you like and give it whatever password you would like. Then you'll need to run this SQL to set up the structure:

CREATE DATABASE `tricks_cake`;

USE `tricks_cake`;

/* Table structure for table `events` */
DROP TABLE IF EXISTS `events`;
CREATE TABLE `events` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `user_id` int(10) unsigned default NULL,
  `location_id` int(10) unsigned default NULL,
  `exp_date` datetime default NULL,
  `title` varchar(255) default '',
  `description` text,
  `url` varchar(255) default '',
  `complete` enum('yes','no') default 'no',
  `created` datetime default NULL,
  `modified` datetime default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

/* Table structure for table `locations` */
DROP TABLE IF EXISTS `locations`;
CREATE TABLE `locations` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `user_id` int(10) unsigned default NULL,
  `title` varchar(255) default '',
  `city` varchar(50) default '',
  `state` varchar(2) default '',
  `zip` int(10) unsigned default NULL,
  `address1` varchar(255) default '',
  `address2` varchar(255) default '',
  `created` datetime default NULL,
  `modified` datetime default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

/* Table structure for table `users` */
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `email` varchar(50) default '',
  `pass` varchar(50) default '',
  `enabled` enum('yes','no') default 'yes',
  `activated` enum('yes','no') default 'no',
  `ac_code` varchar(32) default '',
  `role` enum('admin','user') default 'user',
  `created` datetime default NULL,
  `modified` datetime default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

This SQL is also located in the project at /app/config/schema/structure.sql

Setting up the Project Files

Now that we have our CakePHP project installed and set up with our server environment, let's take a look into the code. We'll need to make some changes to the configuration files.

core.php

This is the main configuration file. You'll need rename or copy the default configuration file (located at /app/config/core.php.default) with the name core.php, in same folder. Next, you need to change some custom settings.

The following lines are to be adjusted in the code already in that file, and help us to send email from the application (needed for sending new user confirmation emails)

// SMTP
    Configure::write( 'smtp_type', 'tls' );
    Configure::write( 'smtp_timeout', 60 );
    Configure::write( 'smtp_host', 'smtp.gmail.com' );
    Configure::write( 'smtp_port', 465 );
    Configure::write( 'smtp_user', 'tricks.cake@gmail.com' );
    Configure::write( 'smtp_password', '' );
    Configure::write( 'smtp_encryption', 'ENC_SSL' );
    Configure::write( 'smtp_mail_from_name', 'noreply' );
    Configure::write( 'smtp_mail_from_addr', 'tricks.cake@gmail.com' );

The values above are for a test/junk GMail account we created just for this. If you planning to send emails from your own Google account, you need to change 3 variables: smtp_user, smtp_password and smtp_mail_from_addr

Now change site_name of your project to the URL it resides on:

// globals
    Configure::write( 'site_name', 'learning-cakephp.dev' );

There are other values you may want to change while extending the project, but you don't need to do this right now. You can read more about CakePHP core.php configuration variables here.

database.php

This is the database configuration file. You'll need to rename or copy this file (located at /app/config/database.php.default) to database.php in the same directory. Then fill out the $default connection array. A finished configuration should look something like this:

var $default = array('driver'      => 'mysql',
                    'persistent'  => false,
                    'host'        => 'localhost',
                    'login'       => 'cakephpuser',
                    'password'    => 'c4k3roxx!',
                    'database'    => 'my_cakephp_project',
                    'prefix'      => '');

These are the database connection details from when you created your database for this project. More information about database configuration.

routes.php

Routing is a feature that maps URLs to controller actions. It was added to CakePHP to make pretty URLs more configurable and flexible. Using Apache’s mod_rewrite is not required for using routes, but it will make your address bar look much more tidy. You don't need to change this file at this time, but you can read about this file (for future use) here.

app_controller.php

This file (located at/app/app_controller.php) is parent class for all controllers in our project. If this file exists, all Controller classes will be inherited from our app_controller. If it doesn't exist, they will be inherited from the libraries default file at /cake/libs/controller/app_controller.php. This is very useful if we need to extend all controllers. You can read more about the App Control here.

app_model.php

This file (located at /app/app_model.php) is parent class for all models in the project. It works just like app_controller, but for all models. If you look into any model code (/app/models) you can see we using $validationSet property (instead of the original $validate property) for creating the list of validation schemes, this allows for more flexible validation data stored in the database. Also we are using app_model to write custom validation rules for use in all models.

address.php

This file (located at /app/views/helpers/address.php) demonstrates how to create a custom helper for your project. You can read more about helpers here.

3rd Party Libraries

We using 3rd party library SwiftMailer for sending out email instead of built in EmailComponent to demonstrate how CakePHP works with 3rd party libraries. SwiftMailerComponent (located at /app/controllers/components/swift_mailer.php) is using for access to SwiftMailer library from our CakePHP project. You can read more about components here.

Additional Structure

And, finally, few words about code structure. CakePHP features Controller, Model, and View classes, but it also features some additional classes and objects that make development in MVC a little quicker and more enjoyable. Components, Behaviors, and Helpers are classes that provide extensibility and reusability to quickly add functionality to the base MVC classes in your applications. Right now we’ll stay at a higher level, so look for the details on how to use these tools later on. You can read more about classes here and more about CakePHP conventions here.

Accessing the Admin Area

  1. Have at least one user registered (yourself).
  2. In your database, find your record in 'users' table.
  3. Change 'role' field value for your user to 'admin' instead 'user'.
  4. Login, and you will now see 'backend' link in navigation bar.

Onward!

Now you are ready to start investigating our tutorial project! Visiting your development domain in your browser should bring up the app. You'll be able to register for an account, activate it, then create/update/delete events and locations as well as view them in the two different views.

Writeable error?

If you get an error about cache files not being writeable, make sure the /app/tmp folder is writeable, and then apply those permissions to all subfolders.

Comments

  1. Permalink to comment#

    Cool! I’m looking forward to future posts. I was intrested in PHP frameworks, but (and I’m sorry to bring this up this early in the comments) compared to Rails they all seem the require a lot of code to do simple things.

    Still my company mainly has PHP programmers and we are not using a framework at this moment. So this series will give me a great insight into Cake!

    • Probably because it’s OO based, which automatically requires more code (of course it seems much better for reusing modules and such).

    • Permalink to comment#

      It only requires more code if you’re using that code once. If you’re using it several times (or if there are several different processes that may or may not include that code chunk), then it saves lots of work.

  2. What sort of limitations, in your experience, come along with CakePHP? Have you used other PHP Frameworks as well? I assume your favorite is Cake, else you wouldn’t be writing about it :)

  3. Khalid
    Permalink to comment#

    I think it’s generally a bad idea to teach this stuff to designers/graphics people.
    The reasoning is two-fold.

    Firstly, people are usually wired one way or the other. That is, they’re great at graphic design and find proper coding/programming(beyond CSS, HTML and perhaps Javascript) confusing or they’re great at programming and can’t make anything look pretty beyond CSS.

    Secondly, teaching from a framework is a terrible idea.
    Why? Because you’re teaching a framework, not the language. By learning the framework you’re simplifying things, which means if the learner runs into a problem, they won’t be able to write code to fix it, they won’t fully understand what they’re doing and they’ll be dependant on that framework. Whilst they could go learn another framework, they’d be starting from scratch and learning PHP proper would be far more of a challenge after learning said framework than if they’d simply gone and learnt PHP at the start.

    • First of all, you assume that no one here knows PHP and that we are all designers. Second, people are definitely not wired on way or another. Take Chris for example. He has damn near mastered HTML, CSS and has a background in print design while at the same time has more than functional knowledge of both PHP, Javascript and especially jQuery. I think that repertoire describes quite a few people who visit this site. People like CakePHP for the same reason they love WordPress or jQuery. They don’t want to reinvent the wheel every time something needs to get done. Plus there’s absolutely nothing wrong with expanding your knowledge base regardless of what you do predominately.

    • Khalid
      Permalink to comment#

      Actually, plenty of people are wired one way or another. The fact that I am means there are others who likely are, too.
      I can write code, but beyond CSS I can do almost nothing when it comes to making content presentable. Even buttons and layouts are an issue for me. I’m sure I’m not the only one.

      I assume that most people here are mainly designers because it’s a design community, not a development community and the vast majority of tutorials focus on CSS, layouts and other graphical things.
      Chris obviously knows HTML and CSS, but a working knowledge of Javascript and PHP is not the same as the level of knowledge he has in HTML, CSS and print layouts. jQuery, like Cake, is a way of simplifying things, so doesn’t count in my eyes.

      There is of course nothing wrong in learning new things at all. If nobody ever learned, no one would be here.
      That said, I believe that if you’re going to learn PHP, learning it properly(versus learning, and being dependant on a framework) is the way to go. Picking up a framework later allows you to do things without repeating previous work(though I prefer saving chunks of code in files and pasting it in, versus relying on a third-party framework) but learning it properly in the beginning would mean that you understand more of what’s going on and can actually create things for yourself.

    • Permalink to comment#

      I actually think you’re wrong about this. Perhaps some people are more wired towards one way or another. But look at Chris. He’s a great designer as well as programmer. Had I not known Chris designed this site (and not seen his previous designs), I would’ve assumed Chris to be a CS (computer science) major/graduate.

      Secondly, I think frameworks are great. While you’re right, they do simply things quite a bit. But if I had to go right now and learn pure javascript and make something fade out when clicked, I probably would’ve never been able to do it without jQuery.

      Frameworks are the way to go in current times. If you can’t adapt to frameworks, you’ll be bypassed.

      And lastly, if you do run into a problem because of a lack of complete knowledge as a direct result of using a simplified framework, there are a ton of resources that can help you. I personally enjoy StackOverflow.com for any programming help and advice. I usually get answers back within minutes of my questions being posted.

    • Permalink to comment#

      I agree with you to an extent…
      I agree its much wiser to learn PHP as a language first, then jump into the frameworks when you feel comfortable writing your own code. However I disagree that people are wired one way or another when it comes to php programming and design. I know many fantasic, talented designers who are master coders and visa versa.

      Thanks for the tutorial!

  4. I’m a PHP guy, mostly since I like the simplicity of it and use WordPress a lot in my development. But I think this is a great resource since many tutorials on frameworks like CakePHP or PHPbb don’t offer this kind of in-depth work flow.

    However, I’m also a hardcore graphics/design guy, and when you simplify the development of web apps for the average freelancer that can’t afford a programmer or the time to learn the intricacies of a language, I think that makes it a quality resource.

    You can always go back and invest more time to learn more about PHP or Ruby later.

    Good post :)

  5. Chris W.
    Permalink to comment#

    I’ve been thinking about using a PHP Framework like Cake or CodeIgniter, since I started developing my own CMS for a social network. I didn’t want to use Typo3 or other CMS, since I wouldn’t have the freedom to change the stuff (at least not with lots of changing in the maincode or making plugins..).

    I was just curious if CakePHP is capable of being a social network backend or if it would take too much time learning CakePHP that well that you can use it (though if it already has CRUD and Validation and all that stuff, I think it would be way easier using that as base than – as you mentioned – reinventing the wheel over and over again)

    • @Chris W. you’re probably looking for something along these lines. http://bit.ly/11GlMP Lots of good stuff in there, but there is an article listed called “Creating a community in five minutes with CakePHP”. It’s not a full-blown back-end with lots of nifty features, but it’s definitely a start.

      — Cheers

    • Chris W.
      Permalink to comment#

      Thanks dude, I’ll take a look at that :)

  6. You can’t shake a stick at someone for going out of their way to explain different types of PHP/Javascript frameworks, especially when you are someone such as myself who often “learns backwards.” I don’t know nearly as much as I would like about how to truly hand code PHP or Javascript themselves. I have read bits of pieces of books that teach PHP and Javascript, but I have a hard time sticking with them. Following Chris’ WordPress screencasts I’ve began to understand why certain pieces of PHP do this, and why some do that. The same goes for picking apart some of his freebies that require jQuery. I’ve began understanding Javscript more as a result of messing around with jQuery So I think for some people, posts like this one about CakePHP are totally valuable. I’ve only known how to write CSS/XHTML for a year and a half, and my skills are mediocre at best, but hey – everybody has their starting points. Chris is the web guy I look up to when it comes to understanding things that by design, are extremely complicated.

    • Permalink to comment#

      One of the best things frameworks have done for me is given me “working examples” to tear apart. I learned OOP from Cake, Flourish and such; I finally got my head wrapped around MVC by following code from the index page of concrete5 all the way through to the controllers and views.

  7. Hello Chris,

    First i want to congratulate you for the new design and better user experience that it offers.

    For me CakePHP is the only PHP framework is the best. Why? Is fast, easy-to-use, comes with the best documentation and of course is #1 between the programmers. If you need help you can search Google or get your doubt responded on Stackoverflow.com.

    Regards,
    Adriano

  8. sophy
    Permalink to comment#

    I use cake more than one year I like cake it easy to use.

  9. I’ve used cake once only it was tough for me..
    But this articles shows me how easy it is..
    Waiting for future post in CAKE
    Thanks a lot

  10. Nice. I started a similar series on my blog http://www.codeforest.net .

    I will surely follow this

  11. Permalink to comment#

    I really don’t like this post, it’s way to complicated and undescribed for any1 not familiar with CakePHP, to bad Chris maybe do the posts on yourself :) No more guest posts…

  12. Paul
    Permalink to comment#

    How does this help you get started with Cake? All’s it does it tell you how to grab an SVN repo with a pre-made project. Bad post.

    PS: CodeIgniter wins hands down over Cake.

    • Permalink to comment#

      This seems to be the 1st part in a series. Although it isn’t 100% clear because of no summary paragraph explaining that tidbit. ;)

      I’ve tried CodeIgniter, and while a seemingly good project, I don’t feel comfortable using it in a production environment.

      When I get home, I’ll work on this Cake tutorial. Thanks for the guest post!

  13. Soma
    Permalink to comment#

    I did look at and try several php frameworks and got to choose Codeigniter, simply because it easy the lightest and easiest to get into, AND has the far better documentation of all. I didn’t regret :D

  14. Permalink to comment#

    Hi,

    Thanks a lot for the post. Looking forward for future posts on Cakephp.

  15. Permalink to comment#

    Personally, coming from the technical/programming side of things trying to learn the graphical stuff too, I still find the more technical articles very helpful. People from all aspects come to Chris’s site. One article may not be as beneficial to one group as it is to the other group(s). He can’t please us all with all articles. He does surveys to find out what we want to learn and I believe tries to cater to what the majority want to learn. I like to use the shopping cart method when choosing which articles to go more in depth with. When I go to the store and going down the isles, I don’t buy everything on the shelves. I know what I need and choose those items I need or want. Same holds true here, if an article doesn’t appeal to you, it probably does to others since Chris does poll his audience for what they want to learn.

    I do agree that it’s probably best to learn the core languages in the long run but there is no reason to shorten the coding time by utilizing frameworks as well. If you look at a lot of job requirements, they often are looking for framework experience as well as core coding. So knowing both is obviously very beneficial. Once you’ve mastered the pure coding side, *yeah right*, no reason, you cannot incorporate frameworks as well to save coding time. Perhaps you build your own for reuse for future projects so you don’t have to reinvent the wheel for each new project. Remember, time is money and if frameworks allow us to complete projects faster then that just means we can complete more projects and make more money :)

    So bottom line, if you don’t like an article, don’t waste your time and wait for articles that relate more to what you need or want to learn.

    ~Jim Zak~

    • Permalink to comment#

      sorry, second paragraph, first sentence should have read:

      I do agree that it’s probably best to learn the core languages in the long run but there is no reason NOT to shorten the coding time by utilizing frameworks as well.

      ~Jim Zak~

    • Permalink to comment#

      true, as long as you understand what’s going on inside the framework. If it’s all a “magic box” to you, then you probably shouldn’t be using it. Your work’s likely to be inefficient, buggy, even insecure. At any rate, you won’t get as much out of it as you could.

    • Permalink to comment#

      dude, that “underground traffic blueprint” page is really lousy. Trying to bring back the old days where you find yourself on a landing page that promises everything, delivers nothing, and won’t let you leave? shi++y.

      To everyone else, save yourselves, don’t visit.

  16. Mike
    Permalink to comment#

    I’m a PHP rookie – I’ve only used it for sending forms, includes and accessing a simple database to produce an online list. I’m looking for something to help me that’s as straightforward as jQuery for javascript.
    From this post, learning CakePHP looks a lot more complicated than learning straight PHP. If that ain’t so, you sure gave me the wrong impression!

  17. A lot of people in the web design/development community wear many hats simply because it comes with the job, javascript/php are light and dynamic languages. Writing and compiling actual Java/C++ code that a desktop developer would be doing is probably better suited to CS graduate comparison.

    I don’t think there’s anything wrong with someone who mainly designs learning these web languages, because if they don’t, they have to pay and depend on someone else to do it. As someone else said, “if you want something done right, do it yourself.” ;)

    The web has an entire ecosystem based off client and server-side technologies, leveraging these skills just makes you more valuable.

  18. Permalink to comment#

    I have learnt cakephp for a while but it just can’t load functinally in my head ,but after take review from your example,it lighter my mind to understand the theory

  19. Permalink to comment#

    Just started with ZendFramework myself because I couldn’t find as much tutorials and posts about CakePHP. Might give it a go as well before I dive into one or the other.

    Good article as usual Chris.

  20. Looks very promising. Actually I’m usually developing for Ruby on Rails. But CakePHP looks better for broader audience.

  21. Okeowo Aderemi
    Permalink to comment#

    To some point i can relate with Khalid Frameworks hinders you from actually learning the main language, but i think Frameworks are quite necessary and very important but effort should be made to least know the basic function and knowledge of the language some times i just thank God for client Frameworks like Jquery it saves 80% of time typing scaring Javascript…no need to reinvent the wheel.

  22. Jay
    Permalink to comment#

    I am a bit confused as to what I am supposed to be taking away from this article. The comments do not help either as most are stating the usual framework talk (I use this, or mine is better). I take it no one has actually read the article or tried out the application, which doesn’t work, by the way. Leading me to believe this is part of a series…

    So, can someone clear up if this is:
    1. A tutorial on how to build a event manager using Cake. Checking out some files, editing some config files, uploading SQL. Nothing groundbreaking or teaching me anything new… Defiantly not showing me CakePHP and how to work with it….
    2. Is it a introduction to Cake by presenting an already made application. The article doesn’t really go into the code itself or the actual application.
    3. A series of a bigger tutorials, and the code will be finalized and go over more in depth at a later time…

    I am confused….

    • Permalink to comment#

      You should look into code ;) every line is commented ;)

      /**
       * Registration method
       * @param POST
       *
       * @return void
       */
          function registration() {
              // setting title
              $this->set( 'title_for_layout', 'New user registration' );
              // is incoming data exists ?
              if ( !empty( $this->data ) ) {
                  // clean incoming data
                  $this->data = Sanitize::clean( $this->data, array( 'encode'=>false ) );
                  // initialize User model
                  $this->User->create();
                  // setting validation scheme
                  $this->User->setValidation( 'registration' );
                  // setting data
                  $this->User->set( $this->data );
                  // validating
                  if ( $this->User->validates() ) {
    • Jay
      Permalink to comment#

      I would like to state that this is a poor article introducing CakePHP and working with it. I am using the Web App From Scratch as a baseline comparison for this site regarding tutorials/how-to, so I expect this article to be similar or up to par.

      May I suggest, next time that you note the processes you took to create this application using CakePHP, then note to review the inner code files, and their locations (where is the code you noted above??). Additionally, note proper setup of Cake PHP after the SVN process as I had the same problem as Daniel Langenakker below.

  23. I’ve done what the article says but when I try to register a user it says it can’t find the registration page. Have I done something wrong?

  24. I personally like Kohana (originally based off CodeIgniter) a lot more than CakePHP. It’s great :)

  25. Samer
    Permalink to comment#

    thanx

  26. Daniel
    Permalink to comment#

    This tutorial didn’t work for me – A first for CSS-tuts. Most others were just fine.

    Can’t get the page to load. Setup the config. Not sure if it’s connecting to Mamp or whatever.

    Giving me 404’s & image not loading on the root.

This comment thread is closed. If you have important information to share, you can always contact me.

*May or may not contain any actual "CSS" or "Tricks".