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)
- Email, Cookie, Security, Session, and Request Handling Components
- Flexible ACL (Access Control List)
- Data Sanitization
- Flexible Caching
- Works from any web site directory, with little to no Apache configuration involved
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:
- Apache web server with enabled mod_rewrite
- PHP version 5 or higher
- SVN client
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.
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', 'firstname.lastname@example.org' ); Configure::write( 'smtp_password', '' ); Configure::write( 'smtp_encryption', 'ENC_SSL' ); Configure::write( 'smtp_mail_from_name', 'noreply' ); Configure::write( 'smtp_mail_from_addr', 'email@example.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:
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.
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.
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.
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.
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.
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.
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
- Have at least one user registered (yourself).
- In your database, find your record in 'users' table.
- Change 'role' field value for your user to 'admin' instead 'user'.
- Login, and you will now see 'backend' link in navigation bar.
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.
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.