CakePHP Application Development - Bari Ahsanul - E-Book

CakePHP Application Development E-Book

Bari Ahsanul

0,0
20,53 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

In Detail

Cake is a rapid development framework for PHP that uses well-known design patterns and provides a structured framework that enables PHP users at all levels to rapidly develop robust web applications, without any loss of flexibility. It means you can code faster, your code is better, and it makes writing Web 2.0-style apps a snap.

This book offers step-by-step instructions to learn the CakePHP framework and to quickly develop and deploy web-based applications. It introduces the MVC pattern and coding styles using practical examples. It takes the developer through setting up a CakePHP development and deployment environment, and develops an example application to illustrate all of the techniques you need to write a complete, non-trivial application in PHP. It aims to assist PHP programmers to rapidly develop and deploy well-crafted and robust web-based applications with CakePHP.

A step-by-step introduction to rapid web development using the open-source MVC CakePHP framework

Approach

This book starts by installing Cake and building our first application, then looking at each main component of a CakePHP application in detail. We then learn how to build Web 2.0 style applications quickly using a case study application. The book is packed with example code and demo applications, so that you can see techniques in action.

Who this book is for

If you already know PHP and want to develop cutting-edge Web 2.0 applications, or see how to write code in a faster, more productive way, then this book is ideal for you.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 352

Veröffentlichungsjahr: 2008

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

CakePHP Application Development
Credits
About the Authors
About the Reviewer
Preface
What This Book Covers
Who is This Book for
Conventions
Reader Feedback
Customer Support
Downloading the Example Code for the Book
Errata
Questions
1. Introduction to CakePHP
What is CakePHP?
A PHP Framework
Common Design Patterns
Rapid Web Development
Works with PHP4 and PHP5
CakePHP is Free and Open Source
Improved Code Structure
Understanding the MVC Pattern
Models
Controllers
Views
How It Works
Faster Development
Less Configuration, More Convention
Auto Code Generation
Quick Access to Related Data
Built-in Commonly Used Functionalities
Versions of CakePHP: 1.1 and 1.2
Summary
2. A Quick Installation
Downloading CakePHP
Time for Action
What Just Happened?
Platform Requirements
Configuring Apache
AllowOverwrite is Set to All
Mod_rewrite Module is Loaded
Setting Up Cake in Web Root
Time for Action
What Just Happened?
Running Cake for the First Time
Summary
3. A Quick App
Making Sure the Oven is Ready
CakeTooDoo: a Simple To-do List Application
Configuring Cake to Work with a Database
Time for Action: Creating and Configuring the Database
What Just Happened?
Writing our First Model
Time for Action: Creating the Task Model
What Just Happened?
Writing our First Controller
Time for Action: Creating the Tasks Controller
What Just Happened?
Viewing All Tasks in CakeTooDoo
Time for Action: Viewing All Tasks
What Just Happened?
Adding a New Task
Time for Action: Creating the Add Task Form
What Just Happened?
Editing a Task
What Just Happened?
Adding Data Validation
Time for Action: Adding Data Validation to Check for Empty Title
What Just Happened?
Deleting a Task from CakeTooDoo
Time for Action: Adding Data Validation
What Just Happened?
Viewing Completed Tasks and Pending Tasks
Time for Action: Viewing Completed and Pending Tasks
What Just Happened?
Formatting Date and Time
Time for Action: Formatting the Created and Modified Time
What Just Happened?
Creating the CakeTooDoo Homepage
Time for Action: CakeTooDoo Homepage
What Just Happened?
Summary
4. Controllers: Programming Application Logic
Interacting with Model
Attaching Models and Controllers
Time for Action: Controller without a Model
What Just Happened?
Action, Parameters, and Views
Interacting with View
Time for Action: Passing Variables to a View
What Just Happened?
Actions and Parameters
Time for Action: Understanding Actions and Parameters
What Just Happened?
Time for Action: Handling more than One Request Parameter
What Just Happened?
How Cake Handles an Incoming Request?
Getting Post Data from the View
Time for Action: Getting Post Data from the View
What Just Happened?
Redirecting
Time for Action: Redirecting from One Action to Another
What Just Happened?
AppController: The Parent Controller
Time for Action: Adding Common Functionalities to all Controllers
What Just Happened?
Working with Components
Time for action: Creating and Using Reusable Components
What Just Happened?
Summary
5. Models: Accessing Data
Setting Up Database and Models
Creating a Model for a Database Table
Time for Action: Creating a Database Table and Its Model
What Just Happened?
Retrieving Data
Using Model to Retrieve Data
Time for Action: Retrieving Data Using Model
What Just Happened?
More on Data Retrieval
More on find()
Writing Complex Conditions
Magic Find Functions
Reading a Single Field
Saving and Updating Data
Saving Data
Time for Action: Saving Data into the Database
What Just Happened?
Updating a Record
Time for Action: Updating a Database Record
What Just Happened?
More on the save() Method
Updating a Single Field
Batch Update
Deleting Data
Deleting a Single Record
Time for Action: Deleting a Single Record
What Just Happened?
Placing Your Own Logic Inside Model
Create and Use Your Own Model Method
Time for Action: Create and Use Your Own Model Method
What Just Happened?
Making Custom SQL Queries
Validating Your Data
Adding Validation to Our Model
Time for Action: Adding Validation to Our Model
What Just Happened?
More on Data Validation
Custom Validation Methods
Summary
6. ORM: Modelling the Table Relationship
Working with Simple Associations
Defining One-To-Many Relationship in Models
Time for Action: Defining One-To-Many Relation
What Just Happened?
Retrieving Related Model Data in One-To-Many Relation
Time for Action: Retrieving Related Model Data
What Just Happened?
Saving Related Model Data in One-To-Many Relation
Time for Action: Saving Related Model Data
What Just Happened?
Adding More than One Association of the Same Type
One-To-One Relation
Customizing Association Characteristics
Working with Complex Associations
Defining Many-To-Many Relationship in Models
Time for Action: Defining Many-To-Many Relation
What Just Happened?
Retrieving Related Model Data in Many-To-Many Relation
Time for Action: Retrieving Related Model Data
What Just Happened?
Saving Related Model Data in Many-To-Many Relation
Time for Action: Saving Related Model Data
What Just Happened?
Deleting Associated Data
Changing Association On The Fly
Summary
7. Views: Creating User Interfaces
Working with Layouts
Creating Custom Layouts
Time for Action: Creating a Custom Layout
What Just Happened?
Using Elements
Creating and Using Element
Time for Action: Creating and Using Elements
What Just Happened?
Working with Helpers
Creating and Using Your Own Helper
Time for Action
What Just Happened?
Creating Forms to Take User Input
Time for Action
What Just Happened?
Summary
8. Using Shells: Get Further, Faster
Setting Up the Cake Shell
Setting Up the Cake Shell in Windows
Time for Action: Setting Up the Cake Shell in Windows
What Just Happened?
Setting Up the Cake Shell in *nix
Time for Action: Setting Up the Cake Shell in *nix
What Just Happened?
Baking an Application
Creating and Configuring the Database
Time for Action: Creating and Configuring the Database
What Just Happened?
Baking Models
Time for Action: Baking Models
What Just Happened?
Baking Controllers
Time for Action: Baking Controllers
What Just Happened?
Baking Views
Time for Action: Baking Views
What Just Happened?
Summary
9. Making Quickwall: The Basics
What is This Quickwall All About?
Setting Up Cake
Time for Action: Setting Up Cake
What Just Happened?
Creating and Connecting the Database
Time for Action
What Just Happened?
Creating and Defining Relationships between Models
Time for Action
What just Happened?
Creating the Basic Controller Actions and Their Views
Time for Action
What Just Happened?
Adding Custom Layout
Time for Action
What Just Happened?
Adding Forms to Add New Questions and Answers
Time for Action
What Just Happened?
Summary
10. Quickwall: User Authentication
Creating the User Model and the Users Controller
Time for Action
What Just Happened?
Making the User Sign Up Process
Time for Action
What Just Happened?
Adding Email Confirmation to Sign Up
Time for Action
What Just Happened?
Integrating Authentication: Database and Models
Time for Action
What Just Happened?
Integrating Authentication: Controllers
Time for Action
What Just Happened?
Integrating Authentication: Views
Time for Action
What Just Happened?
Remembering User with Cookie
Time for Action
What Just Happened?
Summary
11. Quickwall: JavaScript and AJAX
Adding JavaScript Validation
Time for Action
What Just Happened?
AJAX Link to Show Own Questions
Time for Action
What Just Happened?
AJAX AutoComplete to Search Users
Time for Action
What Just Happened?
AJAX Form Submit to View Questions of a User
Time for Action
What Just Happened?
In-Line Editing to Edit Own Answers
Time for Action
What Just Happened?
Summary
12. Quickwall: Making It Better
Making Dates More Readable
Time for Action
What Just Happened?
Creating a User Page
Time for Action
What Just Happened?
Linking the Search Page to the User Page
Time for Action
What Just Happened?
Adding Pagination
Time for Action
What Just Happened?
Adding RSS Feeds
Time for Action
What Just Happened?
Summary
Index

CakePHP Application Development

Ahsanul Bari

Anupom Syam

CakePHP Application Development

Step-by-step introduction to rapid web development using the open-source MVC CakePHP framework

Copyright © 2008 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: July 2008

Production Reference: 1080708

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-847193-89-6

www.packtpub.com

Cover Image by Michelle O'Kane (<[email protected]>)

Credits

Authors

Ahsanul Bari

Anupom Syam

Reviewers

John Mark Diaz

Junal Rahman

Senior Acquisition Editor

David Barnes

Development Editor

Nikhil Bangera

Technical Editors

Ajay Shanker

Rasika Ramesh Sathe

Editorial Team Leader

Mithil Kulkarni

Project Manager

Abhijeet Deobhakta

Project Coordinator

Lata Basantani

Indexer

Rekha Nair

Proofreader

Camille Guy

Production Coordinator

Aparna Bhagat

Cover Work

Aparna Bhagat

About the Authors

Ahsanul Bari is a web application developer from Dhaka, Bangladesh. After graduating from North South University with a bachelor's degree in Computer Science, he has been involved in developing various web applications for local businesses. At a very early stage of his career, he felt the need for tools and techniques to build structured and maintainable web applications. That is when he found out about CakePHP. It was love at first sight and he decided to use CakePHP for his future projects. He never had to look back, and from then on, he has been heavily using CakePHP for all kinds of projects. Most notably, using CakePHP, he developed an ERP solution for companies involved in urban and land development.

Apart from that, he has also 'irregularly' contributed to the CakePHP Documentation Team. He is also an 'irregular' blogger (http://ahsanity.com and http://ahsanity.wordpress.com). Just when people start to think that he has given up blogging, he is known to write a post from nowhere! Among his friends and colleagues, he is known as a fanboy for CakePHP.

Currently, he is working at Trippert Labs, where he has been involved in making a travel-based blogging system, http://www.trippert.com.

This book could not have been possible without the help and support of many people. I would like to thank Hasin Hyder for encouraging us to write this book. Thanks go to David Barnes, our acquisition editor, for always being the best critic, and giving us the push when we needed one. A special thanks to the hardworking people of PacktPub who made this book a reality. Thanks go to all my colleagues at TrippertLabs, who are eagerly waiting for a treat when the book is out. I would also like to thank all my friends for always encouraging me to carry on writing. I would also like to thank the CakePHP community for developing and maintaining such a wonderful framework. But, I will not thank Anupom, the co-author of this book, because I never thank him for anything.

Lastly, I would like to apologize to the three most dearest persons in my life: my mom, my sister, and my jaan Simin. I have written this book during the time that I was supposed to spend with them.

Anupom Syam is a web application developer from Dhaka, Bangladesh. He started programming back in 1998 in C when he was a high school kid. In his early university years, he met Java and fell in love immediately. Through the years, he has become proficient in various aspects of Java (ME, SE, and EE). Early in his career, he was engaged mainly in building localized mobile applications. Over time, his interest in web technologies grew and he did not hesitate to jump onto the Web 2.0 bandwagon. Over the last five years, he has been working with different startups and building web/mobile applications. He currently works as a Development Engineer at Trippert, Inc. where he has been involved in developing a travel-based blogging system http://www.trippert.com (which is developed using CakePHP) as the lead back-end programmer.

He loves to build rich-client web apps with JavaScript/AJAX in the front end and CakePHP/RoR/MySQL in the back end. He still uses Java heavily for his personal fun-time projects. He also maintains blogs: http://anupom.wordpress.com and http://syamantics.com. Besides programming, he is interested in many things, ranging from the most recent scientific discoveries to ancient Vedic philosophies.

First of all, thanks to my parents and my sweet little sister Antara, who stood by patiently while my weekends were occupied with writing inexplicable technical minutiae! A very special thanks to Hasin Hayder, without his inspiration and encouragement I would never find myself writing a book! Thanks to my colleagues, coworkers, and friends— your endless support kept me going. David Barnes, our acquisition editor at Packt, has my deepest respect and gratitude for his patience, understanding, perseverance and suggestions that had really taught me how to write computer books! Not to mention, the heart and soul effort from people of Packt Publication—Abhijeet Deobhakta, Lata Basantani and Nikhil Bangera who made this book (at last) a reality. Also, thanks to our vigorous and veteran technical editors and reviewers: Rasika, Felix, and Junal, without whom this book would be much less accurate.

And finally, I wish to give my sincerest thanks to the developers of the brilliant PHP framework—CakePHP.

About the Reviewer

Junal Rahman is a Computer Science graduate from Independent University of Bangladesh. His areas of expertise include programming with PHP framework and Facebook applications. He has worked for several software companies as a Web Application Developer. During his undergraduate studies, Junal fell in love with .NET programming, but as soon as he started his internship, he fell in love with PHP. He currently works as a Development Engineer at Trippert Labs. At Trippert, Junal collaboratively works to create Facebook applications. He also maintains a blog that can be found at http://junal.wordpress.com. Apart from keeping up with the ever changing field of information technology, he spends much of his private life pursing his interests in screenplay and script writing. In the future, Junal hopes to create films and short dramas, and eventually make his very own movies.

Four years ago, I met a fairy. Since then she has been with me as a shadow. I would like to thank her.

We dedicate this book to all the amazing people of the vibrant CakePHP community, who are working selflessly for other's betterment

Preface

Cake is a rapid development framework for PHP that uses well-known design patterns and provides a structured framework that enables PHP users at all levels to rapidly develop robust web applications, without any loss of flexibility. It means you can code faster, your code is better, and it makes writing Web 2.0-style apps a snap.

This book builds on your knowledge as a PHP developer to provide a fast-paced, step-by-step tutorial in building CakePHP applications. The book is packed with example code and demo applications, so that you can see techniques in action.

What This Book Covers

Chapter 1 will take a look at: what CakePHP is, how CakePHP helps in structuring and maintaining the code, how CakePHP helps in reducing the development time and effort, and which version of Cake should be used.

Chapter 2 will take a quick look at setting up Cake in our local machine.

Chapter 3 will cover how to develop a small application that we'll call the "CakeTooDoo". It will be a simple to-do-list application, which will keep record of the things that we need to do—a shopping list, chapters to study for an exam, etc.

Chapter 4 will cover the nuts and bolts of the CakePHP controller.

Chapter 5 will be a thorough experience of some of the model basics.

Chapter 6 will take an in-depth look at various types of associations and their uses.

Chapter 7 will closely look at the different view components in CakePHP.

Chapter 8 will cover one of the shell scripts called bake. We will build a simple blog using this tool where a user can post articles and comments.

Chapter 9 will look at creating a new web application called 'Quickwall'.

Chapter 10 will cover adding user authentication to our web application—Quickwall.

Chapter 11 will take a look at how to use JavaScript and AJAX with CakePHP.

Chapter 12 will take a look at adding more features to the Quickwall application.

Who is This Book for

If you already know PHP and want to develop cutting-edge Web 2.0 applications, or see how to write code in a faster, more productive way, then this book is ideal for you.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

There are three styles for code. Code words in text are shown as follows: "We can include other contexts through the use of the include directive."

A block of code will be set as follows:

<?php else: ?> <dl> <?php foreach($question['Answer'] as $answer) : ?> <dt><span><?php e($answer['User']['username']); ?></span></dt> <dd>

When we wish to draw your attention to a particular part of a code block, the relevant lines or items will be made bold:

<?php if($loggedIn): ?> <?php e($html->link('Your Questions', array('controller' => 'users', 'action' => 'show', $loggedIn))); ?>| <?php e($html->link('Search', array('controller' =>

Any command-line input and output is written as follows:

# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample /etc/asterisk/cdr_mysql.conf

New terms and important words are introduced in a bold-type font. Words that you see on the screen, in menus or dialog boxes for example, appear in our text like this: "clicking the Next button moves you to the next screen".

Note

Important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader Feedback

Feedback from our readers is always welcome. Let us know what you think about this book, what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply drop an email to <[email protected]>, making sure to mention the book title in the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer Support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the Example Code for the Book

Visit http://www.packtpub.com/files/code/3896_Code.zip to directly download the example code.

The downloadable files contain instructions on how to use them.

Errata

Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing this you can save other readers from frustration, and help to improve subsequent versions of this book. If you find any errata, report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the Submit Errata link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata are added to the list of existing errata. The existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Questions

You can contact us at <[email protected]> if you are having a problem with some aspect of the book, and we will do our best to address it.

Chapter 1. Introduction to CakePHP

Most technical books start by outlining the good features of the concerned technology, so that the reader is convinced that the technology is worth learning, and the book is worth reading. But unlike those books, this one starts with a warning:

"Once readers have gone through the book, there will be no turning back! Web development will never be the same again. Developing a web application will become so easy, that it might make the readers very lazy. As a matter of fact, readers might even forget the basic syntaxes of PHP! And the word Cake will have a completely new meaning to them"

If you are still determined to read along, you are welcome! But do not blame us later; you have been warned!

We are going to start our journey into CakePHP by trying to understand what CakePHP is and how it will help us develop web applications faster, that are also easy to manage and maintain. To be more specific, in this chapter, we are going to see:

What is CakePHP?How CakePHP helps in structuring and maintaining the code?How CakePHP helps in reducing the development time and effort?And, which version of Cake should be used?

What is CakePHP?

According to the official CakePHP website (http://cakephp.org):

"Cake is a rapid development framework for PHP which uses commonly known design patterns like Active Record, Association Data Mapping, Front Controller and MVC. Our primary goal is to provide a structured framework that enables PHP users at all levels to rapidly develop robust web applications, without any loss to flexibility."

Someone who is new to frameworks might not understand parts of the definition. But understanding a few key terms will make the job much easier.

A PHP Framework

A PHP framework is a collection of code, libraries, classes, and run-time environment that helps developers build web applications faster. The main idea behind using frameworks is to provide the developers with commonly used functionalities and a basic structure that they can build their application on. Most PHP developers, who have some experience, have their own set of libraries and structure to help them develop faster, as they can use their code base (and experience) from one project to another. But, building a web application on an open-source framework like CakePHP has its obvious benefits. By doing so, the developers not only use their own experience, but also the experiences of many other developers who have used and developed the framework. Also, the framework is much more reliable as it is used and tested by many application developers. Besides, using a framework like CakePHP has the advantage that all the developers involved in a project have to follow the same conventions and rules to structure the application. It makes it very easy for new developers to settle down if they are familiar with the conventions of the framework.

Common Design Patterns

A design pattern is a general solution to a commonly occurring problem in web development. A design pattern is not a complete code, rather it is a description for how to solve a problem that can be used in many different situations. In web development, there are many common design patterns that are used to solve repeating and common problems. CakePHP has many of these design patterns integrated into it. Some of them are mentioned in the above definition: Active Record, Association Data Mapping, Front Controller and MVC. Among them, MVC, which stands for Model View Controller, is at the core of CakePHP. We will soon discuss MVC, and other important design patterns, in this chapter. The other design patterns will be discussed throughout the book.

Rapid Web Development

The integration of common design patterns into CakePHP means that developers need not waste time in trying to solve problems that are commonly present in almost all web projects. These are already solved in CakePHP! As a result, the developer can focus on the specific business logic of the application, rather than being busy in trying to reinvent the wheel. This results in much faster and rapid application development.

Works with PHP4 and PHP5

Though it is not mentioned in the definition, CakePHP works out of the box with both PHP4 and PHP5. So, as long the developer follows the CakePHP convention, their application will be easily portable between the two versions of PHP. Unlike many PHP frameworks, the developer need not worry about compatibility issues. Web servers with either PHP4 or PHP5 will gladly run CakePHP-based applications. But having said that, it is always a better idea to use PHP5 if compatibility is not an issue for the project. Since most CakePHP apps are custom applications, PHP4 compatibility is normally not an important factor. So, using PHP5 for CakePHP application is definitely recommended.

CakePHP is Free and Open Source

Yes, that is right: CakePHP is an open-source project and it is free for anyone who wants to use it. It is distributed under the MIT License. That means that not only will people be able to use it free of charge, but they will also be able to look at the source code of CakePHP, and find out how the magic works.

Now, that we have a better understanding of the main concepts behind CakePHP, do have a second look at the definition! It should be much easier to understand. More importantly, we now have a good understanding of what to expect from CakePHP, as we now know what it is!

Improved Code Structure

PHP is a wonderful programming language for server-side web development. One of its benefits is that PHP is very easy to learn. Any person with some basic programming skills (even without it) can start making dynamic web pages. PHP gives developers a lot of flexibility in the way that they code. In other words, it does not restrict the developer to follow a certain structure. This is also one of its major drawbacks. As inexperienced programmers start to built bigger applications, most of the time, the code becomes so unstructured that it becomes very hard to debug or modify even a small change. The same situation also occurs with experienced PHP developers, when the application becomes complex. The situation gets even worse, when multiple developers work in a single project, each following their own way of coding. The main reason for this problem is that PHP does not restrict the developers to follow a certain structure.

CakePHP helps to solve this problem by restricting the developers to follow a strict structure. By doing so, it makes sure that the overall code of the project has a structure that is easy to manage and maintain.

The most important design pattern that CakePHP uses to maintain a structured code is the MVC (Model View Controller) pattern

Understanding the MVC Pattern

The MVC (Model View Controller) pattern is a commonly used design pattern in software development, where the code is separated into three major parts: models, views, and controllers. The exact purpose of each part depends on the implementation, as it may vary from one framework to another. Here, we are going to describe the way CakePHP implements the MVC pattern. So, this is not a general discussion on MVC pattern, rather we are only going to see Cake's own MVC implementation. As we have already mentioned, CakePHP separates the code into three separate parts: models, views, and controllers.

Models

In CakePHP, a model represents a particular database table. Each database table should have a model representing it. So, in CakePHP, every database table has its own model. All PHP code related to accessing, adding, modifying or deleting records from the table are situated in the model. The model also contains code that defines its relationship with other models. Other than that, the model also defines the data validation rules when adding or updating data for that model. Model can be thought of as the data layer of the application. The model is also the place where the business logic related to the model should be defined. For example, if we have a model to represent cars, all actions related to it like buy car, sell car etc. should be defined in the model. Models should be the place where the core business logic of an application are defined.

Controllers

Controllers, in CakePHP, control the application flow or logic of the application. Each web request is directed to a particular controller where the user input (POST or GET data) is accepted. The controller logic then decides what response is generated. The controller logic normally contains calls to models to access data, and also other functionalities like access control check etc. Lastly, the controller passes the response (output) to the view (discussed next). Controller can be thought as the control logic layer of the application. As mentioned above, the model should have all the business logic of an application. The controllers should just delegate the actions to the model, and be light. This design philosophy is sometimes referred to as the "fat models and thin controllers".

Views

Views are the outputs or responses that are sent back to the user once a request is processed. They basically consists of markup (like HTML) code with embedded PHP code, but they can also be other forms of output like XML, PDF document etc. depending on the situation. Views can be thought as the presentation layer of the application.

How It Works

So now that we have a better understanding of all the three components of CakePHP MVC, let's see how these three components work together to handle a request.

The diagram above shows how it all works together:

The request is dispatched to the controller, with user data (POST and GET data).The controller processes the request, and calls the model to access the data.The model responses to the controller's call, by sending or storing data.The controller then sends the output data to the view.The view outputs the data in the proper format.

As we have already seen earlier, using the MVC pattern helps to structure the code into modular segments. This allows the developer to quickly make any changes if required and as a result, debugging and modification becomes a much easier job. Using MVC also has the added benefit of reusing code. For example, a single model code can be used in any controller that needs to access the data in that model.

Another benefit of MVC is that it results in a shorter development time. But MVC is not the only tool that CakePHP has to quicken the development time. There are many more as we discuss next.

Faster Development

One of the main reasons that most of the modern web applications are built on a framework is for faster development. Using frameworks, like CakePHP, it is possible to develop web applications much faster than it would have been possible using raw PHP. Other than the MVC pattern, CakePHP comes with many other tricks and magic that aids in faster web development.

Less Configuration, More Convention

One of the main philosophies of the CakePHP design is to have minimum number of configurations. Configurations are normally required to make sure that the system is properly set up, and behaving the way we want it. But with CakePHP, these configurations are kept to minimum. In fact, the only thing that we need to get CakePHP running is to let it know the name of the database to use, and nothing else need to be specified!

CakePHP was designed in a way that it relied more on conventions than on configurations. Conventions are stuffs like the name of the database fields, name and locations of models, controllers and views. If these are named and placed according to the CakePHP conventions, Cake will automatically find and use them properly. That is why it is important to understand the naming conventions that CakePHP uses. Once we are familiar with that, we will never have to worry about configuration again.

Auto Code Generation

Just imagine how much easier it would be if we have a working code base that is specific to the application we want to develop, even before we have started to write a single line of code. Well, with CakePHP, we do not need to imagine anymore, because it is a reality. CakePHP built-in code generator is more commonly known as the baking script. All we need to do is to specify the database tables for the project, and start baking! It will automatically create the models, controllers, and views that we need. Using this generated code, we will have a running application that can insert, edit, list, and delete data from all the database tables.

Quick Access to Related Data

CakePHP has useful design patterns integrated that makes it very easy to access and modify data from the database. It has a very neat data abstraction layer, and also has support for association data mapping.

With Cake's data abstraction layer,, we will never need to write SQL queries again, to retrieve or modify data. By calling appropriate model functions, we will be able to access the data very easily. All data will be returned in nicely formatted associated arrays without any hassle.

Association data mapping is a technique by which CakePHP is able to fetch data from not only a single table, but if necessary, all (or selected) related data from other database tables as well. For example, suppose we have a posts table that contains blog posts, and another table named comments that contain all the comments. Now, if we want to fetch a single post along with all the comments of that post, all we need to do is to call a single model function that will not only return the post, but also all the related comments. CakePHP will automatically fetch all the related data from other tables, and send them along with the desired data. We no longer need to write complex or multiple SQL statements to do it.

Built-in Commonly Used Functionalities

Other than the above mentioned features, CakePHP has loads of other functionalities so that the developers do not have to waste time coding solutions to commonly found features in web applications. Some of them are mentioned below:

Built-in Data Validation: CakePHP has a very extensive data validation mechanism, where we just need to specify the valid data type, and CakePHP will handle the rest.Custom Page Layout: Most of the time, an application has a common look-and-feel for all the pages. Using CakePHP's layout functionality, we just need to put the layout file in the proper location, and all the pages will use it.Access Control: If we are building an application where we need to control the access of different parts of the application, depending on the user type, we can easily accomplish this by using the Access Control List.AJAX Helper: Adding AJAX functionalities using the built-in AJAX helper (that uses Prototype and Scriptaculous) is very easy. This can be accomplished without writing a single line of JavaScript.

Other than these, there are other many useful features that help in developing an application in record time, using CakePHP.

Versions of CakePHP: 1.1 and 1.2

Now that we know all the exciting features of CakePHP, the next thing is to decide on which CakePHP version to use. There are two major versions present at the moment: the more stable 1.1, and the exciting new 1.2. Though 1.2 has been around for quite sometime, it is still in beta stage. But having said that, the Cake community is very confident of this version, and proudly declares that 1.2 is one of the most stable beta software out there. There are many production quality web applications that are running on 1.2. And, the new features and enhancements made to this version are too good to not use it. As a result, we will be using the 1.2 version in this book. Hopefully, by the time this book is out, the stable version of 1.2 will be out too. So, without any delay, download the latest CakePHP 1.2, and move to the next chapter to find out how to install it.

Summary

In this chapter, we saw what CakePHP is, and how it can help us to develop web applications that are well structured, and that are also fast to develop. We also discussed what we understand by a PHP framework and what design patterns are. We looked closely into the MVC pattern, which is an important part of CakePHP and helps to organize the code neatly. Then, we discussed the features of CakePHP that helps in developing applications faster. Lastly, we saw why we will be using CakePHP 1.2 for all the chapters in this book.

Chapter 2. A Quick Installation

In the first chapter, we learned how CakePHP can help us build web applications that are well structured, and that can be developed rapidly. The next logical step for us is to install Cake, so that we can start baking delicious and yummy Cake applications.

In this chapter, we take a quick look at setting up Cake in our local machine. As we will see, installing and setting up Cake in the local machine is not a very difficult task. If we are already familiar with developing web applications in Apache, MySQL, and PHP-based environments, this chapter should be a simple walk through.

In this chapter, we will:

Download the latest version of CakePHP 1.2Other software that we need to run CakeConfigure Apache to run CakePlace Cake in the web root of ApacheRun Cake for the first time

Downloading CakePHP

In this section, we will see how to download the latest version of CakePHP 1.2. Though this is a simple task, this section has another objective. You will see that this section is divided into two parts: Time for Action and What Just Happened. Throughout the rest of the book, we will be using this format to accomplish different tasks. In the Time for Action segment, we will show the steps involved in completing the task. In other words, the Time for Action segment will take you through the step-by-step process of what needs to be done. In the What Just Happened segment, we are going to discuss in detail about why we did take the steps. So, without any delay, here is the first of many Time for Actions to come:

Time for Action

Open up a web browser, and point to http://cakephp.org/. We will land in the homepage of CakePHP:

In the Get it now! tab, click on the 1.2.x.xxx link (x's will be numbers, depending on the latest 1.2 release). This link is located just below the Download button, on the right of the page.

This will take you to a page that will have a list of links, as shown in the following screenshot. The latest version of CakePHP 1.2 will be highlighted. From the list, click on the compressed file type (.zip, .tar.bz2 and .tar.gz) of your choice, to download.Once you click on it, you will be taken to the donation page, shown in the following screenshot. You have the choice to donate some money to the Cake Software Foundation. This money will be used in the betterment of CakePHP. So, if you think you can help, do not hesitate to. Or, else you can choose the No Thanks option.This will finally take you to the download page (shown in the following screenshot), that will have a link at the bottom Download Latest Release. Clicking on the link will open up a dialog box that will ask you to either save it or open it. Choose to save, and point to a suitable location to save the file. Lastly, press OK. Your cake should be on its way!

What Just Happened?

In this section, we saw the steps needed to download Cake from the official CakePHP site. The steps are all self explained. So, we do not need to really describe anything more here.

But, in later What Just Happened segments, we will be giving insights to why we took the actions in the corresponding Time for Action.

Platform Requirements

In this quick installation, it will be assumed that we are using Apache as our web server, MySQL as our database server, and of course PHP. To run Cake, the minimum version of PHP that we will need is PHP 4.3.2. All later versions of PHP, including 4.3.2, should work fine with CakePHP. CakePHP is also known to work with other web servers and database servers as well. Before you proceed further, please make sure that your local machine fulfils the requirements.

Configuring Apache

There is some tweaking that we need to perform in order to make sure that Apache runs CakePHP applications smoothly. Many Apache installations may not require the following tweaking, as they might be set as default, but it is always a good idea to check if the following settings are present.

AllowOverwrite is Set to All

We need to make sure that the web root directory, or the directory in which we plan to keep CakePHP has AllowOverwrite set to all. We can do this by checking Apache's main configuration file http.conf. This file should be located in the directory called conf, where we have installed Apache. In this file, there should be <Directory> option for the web root directory. As the following configuration shows, the web root (which is L:/wamp/www for this particular installation) has a Directory entry in which the AllowOverwrite option is set to all. If the directory under web root, in which we plan to keep Cake, has a directory entry, we need to check that one too.

<Directory "L:/wamp/www"> Options Indexes FollowSymLinks AllowOverride all Order Deny,Allow Deny from all Allow from 127.0.0.1 </Directory>

Mod_rewrite Module is Loaded

We also need to make sure that the Apache is loading the mod_rewrite module. To do this, we again have to check the http.conf file. There should be a section in the http.conf file named Dynamic Shared Object (DSO) Support, where all the different modules that are loaded by Apache are listed. The modules that are not being loaded are commented out with #