SlideShare a Scribd company logo
Cakephp tutorial
CakePHP
i
AbouttheTutorial
CakePHP is an open-source framework for PHP. It is intended to make developing,
deploying and maintaining applications much easier.
CakePHP is based on an MVC-like architecture that is both powerful and easy to grasp.
Models, Views, and Controllers guarantee a strict but natural separation of business logic
from data and presentation layers.
Audience
This tutorial is meant for web developers and students who would like to learn how to
develop websites using CakePHP. It will provide a good understanding of how to use this
framework.
Prerequisites
Before you proceed with this tutorial, we assume that you have knowledge of HTML, Core
PHP, and Advance PHP. We have used CakePHP version 3.2.7 in all the examples.
Copyright&Disclaimer
 Copyright 2016 by Tutorials Point (I) Pvt. Ltd.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
CakePHP
ii
TableofContents
About the Tutorial..................................................................................................................................i
Audience ................................................................................................................................................i
Prerequisites ..........................................................................................................................................i
Copyright & Disclaimer...........................................................................................................................i
Table of Contents ..................................................................................................................................ii
1. CAKEPHP — OVERVIEW .....................................................................................................1
CakePHP Request Cycle .........................................................................................................................1
2. CAKEPHP — INSTALLATION................................................................................................3
3. CAKEPHP — FOLDER STRUCTURE ......................................................................................4
4. CAKEPHP — CONFIGURATION ...........................................................................................6
General Configuration ...........................................................................................................................6
Databases Configuration .......................................................................................................................7
5. CAKEPHP — EMAIL CONFIGURATION ................................................................................9
6. CAKEPHP — ROUTING......................................................................................................11
Connecting Routes...............................................................................................................................11
Passed Arguments...............................................................................................................................13
7. CAKEPHP — GENERATING URLS.......................................................................................16
8. CAKEPHP — REDIRECT ROUTING .....................................................................................18
9. CAKEPHP — CONTROLLERS..............................................................................................20
AppController......................................................................................................................................20
Controller Actions................................................................................................................................21
CakePHP
iii
Redirecting ..........................................................................................................................................21
Loading Models ...................................................................................................................................24
10. CAKEPHP — VIEWS ..........................................................................................................25
View Templates...................................................................................................................................25
View Variables.....................................................................................................................................25
11. CAKEPHP — EXTENDING VIEWS.......................................................................................28
12. CAKEPHP ─ VIEW ELEMENTS............................................................................................30
13. CAKEPHP ─ VIEW EVENTS.................................................................................................33
14. CAKEPHP — WORKING WITH DATABASE .........................................................................34
Insert a Record ....................................................................................................................................34
15. CAKEPHP ─ VIEW A RECORD ............................................................................................37
16. CAKEPHP — UPDATE A RECORD.......................................................................................40
17. CAKEPHP ─ DELETE A RECORD .........................................................................................44
18. CAKEPHP — SERVICES......................................................................................................47
Authentication ....................................................................................................................................47
19. CAKEPHP — ERRORS & EXCEPTION HANDLING................................................................52
Errors and Exception Configuration .....................................................................................................52
20. CAKEPHP — LOGGING .....................................................................................................55
21. CAKEPHP — FORM HANDLING.........................................................................................59
22. CAKEPHP — INTERNATIONALIZATION..............................................................................65
Email ...................................................................................................................................................68
CakePHP
iv
23. CAKEPHP — SESSION MANAGEMENT..............................................................................73
Accessing Session Object .....................................................................................................................73
Writing Session Data ...........................................................................................................................73
Reading Session Data ..........................................................................................................................73
Delete Session Data.............................................................................................................................74
Destroying a Session............................................................................................................................74
Renew a Session..................................................................................................................................75
Complete Session ................................................................................................................................75
24. CAKEPHP — COOKIE MANAGEMENT ...............................................................................80
Write Cookie........................................................................................................................................80
Read Cookie ........................................................................................................................................80
Check Cookie .......................................................................................................................................80
Delete Cookie ......................................................................................................................................81
25. CAKEPHP — SECURITY .....................................................................................................86
Encryption and Decryption ..................................................................................................................86
CSRF ....................................................................................................................................................86
Security Component............................................................................................................................87
26. CAKEPHP — VALIDATION.................................................................................................90
Validation Methods.............................................................................................................................90
27. CAKEPHP — CREATING VALIDATORS................................................................................93
Validating Data....................................................................................................................................93
CakePHP
5
CakePHP is an open source MVC framework. It makes developing, deploying and maintaining
applications much easier. CakePHP has number of libraries to reduce the overload of most
common tasks. Following are the advantages of using CakePHP.
 Open Source
 MVC Framework
 Templating Engine
 Caching Operations
 Search Engine Friendly URLs
 Easy CRUD (Create, Read, Update, Delete) Database Interactions.
 Libraries and Helpers
 Built-in Validation
 Localization
 Email, Cookie, Security, Session, and Request Handling Components
 View Helpers for AJAX, JavaScript, HTML Forms and More
CakePHPRequestCycle
The following illustration describes how a Request Lifecycle works:
1. CakePHP — Overview
CakePHP
6
A typical CakePHP request cycle starts with a user requesting a page or resource in your
application. At a high level, each request goes through the following steps:
 The webserver rewrite rules direct the request to webroot/index.php.
 Your application’s autoloader and bootstrap files are executed.
 Any dispatch filters that are configured can handle the request, and optionally
generate a response.
 The dispatcher selects the appropriate controller & action based on routing rules.
 The controller’s action is called and the controller interacts with the required Models
and Components.
 The controller delegates response creation to the View to generate the output
resulting from the model data.
 The view uses Helpers and Cells to generate the response body and headers.
 The response is sent back to the client.
CakePHP
7
Installing CakePHP is simple and easy. You can install it from composer or you can download
it from github — https://github.com/cakephp/cakephp/releases. We will further understand
how to install CakePHP in WampServer. After downloading it from github, extract all the files
in a folder called “CakePHP” in WampServer. You can give custom name to folder but we have
used “CakePHP”.
Make sure that the directories logs, tmp and all its subdirectories have write permission
as CakePHP uses these directories for various operations.
After extracting it, let’s check whether it has been installed correctly or not by visiting the
following URL in browser: http://localhost:85/CakePHP/
The above URL will direct you to the screen as shown below. This shows that CakePHP has
successfully been installed.
2. CakePHP – Installation
CakePHP
8
Take a look at the following screenshot. It shows the folder structure of CakePHP.
The following table describes the role of each folder:
Folder
Name
Description
bin The bin folder holds the Cake console executables.
config
The config folder holds the (few) configuration files CakePHP uses.
Database connection details, bootstrapping, core configuration files and
more should be stored here.
logs
The logs folder normally contains your log files, depending on your log
configuration.
plugins The plugins folder is where the Plugins your application uses are stored.
src
The src folder will be where you work your magic: It is where your
application’s files will be placed. CakePHP’s src folder is where you will do
most of your application development. Let’s look a little closer at the
folders inside src.
 Console Contains the console commands and console tasks for your
application.
 Controller Contains your application’s controllers and their
components.
3. CakePHP — Folder Structure
CakePHP
9
 Locale Stores string files for internationalization.
 Model Contains your application’s tables, entities and behaviors.
 View Presentational classes are placed here: cells, helpers, and
template files.
 Template Presentational files are placed here: elements, error
pages, layouts, and view template files.
tests The tests folder will be where you put the test cases for your application.
tmp
The tmp folder is where CakePHP stores temporary data. The actual data
it stores depends on how you have CakePHP configured, but this folder is
usually used to store model descriptions and sometimes session
information.
vendor
The vendor folder is where CakePHP and other application dependencies
will be installed. Make a personal commitment not to edit files in this
folder. We can’t help you if you’ve modified the core.
webroot
The webroot directory is the public document root of your application. It
contains all the files you want to be publically reachable.
CakePHP
10
CakePHP comes with one configuration file by default and we can modify it according to our
needs. There is one dedicated folder “config” for this purpose. CakePHP comes with different
configuration options.
GeneralConfiguration
The following table describes the role of various variables and how they affect your CakePHP
application.
Variable Name Description
debug
Changes CakePHP debugging output.
false = Production mode. No error messages, errors, or warnings
shown.
true = Errors and warnings shown.
App.namespace The namespace to find app classes under.
App.baseUrl
Un-comment this definition if you don’t plan to use Apache’s
mod_rewrite with CakePHP. Don’t forget to remove your
.htaccess files too.
App.base
The base directory the app resides in. If false, this will be auto
detected.
App.encoding
Define what encoding your application uses. This encoding is used
to generate the charset in the layout, and encode entities. It
should match the encoding values specified for your database.
App.webroot The webroot directory.
App.wwwRoot The file path to webroot.
App.fullBaseUrl
The fully qualified domain name (including protocol) to your
application’s root.
App.imageBaseUrl Web path to the public images directory under webroot.
App.cssBaseUrl Web path to the public css directory under webroot.
App.jsBaseUrl Web path to the public js directory under webroot.
App.paths
Configure paths for non-class based resources. Supports the
plugins, templates, locales subkeys, which allow the definition
of paths for plugins, view templates and locale files respectively.
Security.salt
A random string used in hashing. This value is also used as the
HMAC salt when doing symmetric encryption.
Asset.timestamp
Appends a timestamp which is last modified time of the particular
file at the end of asset files URLs (CSS, JavaScript, Image) when
using proper helpers. Valid values:
 (bool) false - Doesn’t do anything (default)
 (bool) true - Appends the timestamp when debug is true
4. CakePHP – Configuration
CakePHP
11
 (string) ‘force’ - Always appends the timestamp
DatabasesConfiguration
Database can be configured in config/app.php file. This file contains a default connection
with provided parameters which can be modified as per our choice. The below screenshot
shows the default parameters and values which should be modified as per the requirement.
Let’s understand each parameter in detail:
Key Description
className
The fully namespaced class name of the class that represents the
connection to a database server. This class is responsible for
loading the database driver, providing SQL transaction
mechanisms and preparing SQL statements among other things.
driver
The class name of the driver used to implements all specificities
for a database engine. This can either be a short classname using
plugin syntax, a fully namespaced name, or a constructed driver
instance. Examples of short classnames are Mysql, Sqlite,
Postgres, and Sqlserver.
persistent Whether or not to use a persistent connection to the database.
host The database server’s hostname (or IP address).
username Database username
password Database password
CakePHP
12
database Name of Database
port (optional) The TCP port or Unix socket used to connect to the server.
encoding
Indicates the character set to use when sending SQL statements
to the server like ‘utf8’ etc.
timezone Server timezone to set.
schema
Used in PostgreSQL database setups to specify which schema to
use.
unix_socket
Used by drivers that support it to connect via Unix socket files. If
you are using PostgreSQL and want to use Unix sockets, leave
the host key blank.
ssl_key The file path to the SSL key file. (Only supported by MySQL).
ssl_cert
The file path to the SSL certificate file. (Only supported by
MySQL).
ssl_ca
The file path to the SSL certificate authority. (Only supported by
MySQL).
init
A list of queries that should be sent to the database server as
when the connection is created.
log
Set to true to enable query logging. When enabled queries will be
logged at a debug level with the queriesLog scope.
quoteIdentifiers
Set to true if you are using reserved words or special characters
in your table or column names. Enabling this setting will result in
queries built using the Query Builder having identifiers quoted
when creating SQL. It decreases performance.
flags
An associative array of PDO constants that should be passed to
the underlying PDO instance.
cacheMetadata
Either boolean true, or a string containing the cache configuration
to store meta data in. Having metadata caching disable is not
advised and can result in very poor performance.
CakePHP
13
Email can be configured in file config/app.php. It is not required to define email
configuration in config/app.php. Email can be used without it; just use the respective methods
to set all configurations separately or load an array of configs. Configuration for Email defaults
is created using config() and configTransport().
Email Configuration Transport
By defining transports separately from delivery profiles, you can easily re-use transport
configuration across multiple profiles. You can specify multiple configurations for production,
development and testing. Each transport needs a className. Valid options are as follows:
 Mail — Send using PHP mail function

 Smtp — Send using SMTP

 Debug — Do not send the email, just return the result
You can add custom transports (or override existing transports) by adding the appropriate
file to src/Mailer/Transport. Transports should be named YourTransport.php, where
'Your' is the name of the transport. Following is the example of Email configuration transport.
Example
'EmailTransport' => [
'default' => [
'className' => 'Mail',
// The following keys are used in SMTP transports
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'tls' => null,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
],
5. CakePHP – Email Configuration
CakePHP
14
Email Delivery Profiles
Delivery profiles allow you to predefine various properties about email messages from your
application and give the settings a name. This saves duplication across your application and
makes maintenance and development easier. Each profile accepts a number of keys. Following
is an example of Email delivery profiles.
Example
'Email' => [
'default' => [
'transport' => 'default',
'from' => 'you@localhost',
],
],
CakePHP
15
End of ebook preview
If you liked what you saw…
Buy it from our store @ https://store.tutorialspoint.com

More Related Content

PDF
Php tutorial
PDF
php lessons
PDF
PL_SQL
PDF
Javascript tutorial
PDF
Javascript tutorial
PDF
Php7 tutorial
PDF
Php tutorial
PDF
Asp.net mvc tutorial
Php tutorial
php lessons
PL_SQL
Javascript tutorial
Javascript tutorial
Php7 tutorial
Php tutorial
Asp.net mvc tutorial

What's hot (9)

PDF
Chef tutorial
PDF
Cprogramming tutorial
PDF
Cprogramming tutorial
PDF
Cprogramming tutorial
PDF
Gprs tutoialc
PDF
Learn c programming
PDF
Sap abap tutorial
PDF
Html5 tutorial
Chef tutorial
Cprogramming tutorial
Cprogramming tutorial
Cprogramming tutorial
Gprs tutoialc
Learn c programming
Sap abap tutorial
Html5 tutorial
Ad

Similar to Cakephp tutorial (20)

PDF
Cakephp manual-11
PDF
Cake PHP Training Institute, Ghaziabad
PDF
Manual 5
PPTX
Ei cakephp
PPTX
Cakeph pppt
ODP
Don't Code, Bake. An introduction to CakePHP ~PHP Hampshire Oct 2014
PDF
5503 cake php-tutorial-no-1-from-ibm
PPT
Intro to CakePHP 1.3
PDF
Introduction to CakePHP
PDF
Introduction to CakePHP
PPTX
cakephp UDUYKTHA (1)
PDF
Rapid Development With CakePHP
PDF
Cake php cookbook
PDF
Building Restful Web App Rapidly in CakePHP
PPT
9 Awesome cake php tutorials and resources
ODP
Get going with CakePHP Framework at gnuNify 2010
PDF
An Introduction to CakePHP
PDF
CakePHP
PDF
PDF
CakePHP: An Introduction
Cakephp manual-11
Cake PHP Training Institute, Ghaziabad
Manual 5
Ei cakephp
Cakeph pppt
Don't Code, Bake. An introduction to CakePHP ~PHP Hampshire Oct 2014
5503 cake php-tutorial-no-1-from-ibm
Intro to CakePHP 1.3
Introduction to CakePHP
Introduction to CakePHP
cakephp UDUYKTHA (1)
Rapid Development With CakePHP
Cake php cookbook
Building Restful Web App Rapidly in CakePHP
9 Awesome cake php tutorials and resources
Get going with CakePHP Framework at gnuNify 2010
An Introduction to CakePHP
CakePHP
CakePHP: An Introduction
Ad

More from HarikaReddy115 (20)

PDF
Dbms tutorial
PDF
Data structures algorithms_tutorial
PDF
Wireless communication tutorial
PDF
Cryptography tutorial
PDF
Cosmology tutorial
PDF
Control systems tutorial
PDF
Computer logical organization_tutorial
PDF
Computer fundamentals tutorial
PDF
Compiler design tutorial
PDF
Communication technologies tutorial
PDF
Biometrics tutorial
PDF
Behavior driven development_tutorial
PDF
Basics of computers_tutorial
PDF
Basics of computer_science_tutorial
PDF
Basic electronics tutorial
PDF
Auditing tutorial
PDF
Artificial neural network_tutorial
PDF
Artificial intelligence tutorial
PDF
Antenna theory tutorial
PDF
Analog communication tutorial
Dbms tutorial
Data structures algorithms_tutorial
Wireless communication tutorial
Cryptography tutorial
Cosmology tutorial
Control systems tutorial
Computer logical organization_tutorial
Computer fundamentals tutorial
Compiler design tutorial
Communication technologies tutorial
Biometrics tutorial
Behavior driven development_tutorial
Basics of computers_tutorial
Basics of computer_science_tutorial
Basic electronics tutorial
Auditing tutorial
Artificial neural network_tutorial
Artificial intelligence tutorial
Antenna theory tutorial
Analog communication tutorial

Recently uploaded (20)

PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Lesson notes of climatology university.
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Complications of Minimal Access Surgery at WLH
PDF
Sports Quiz easy sports quiz sports quiz
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
RMMM.pdf make it easy to upload and study
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
master seminar digital applications in india
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
O7-L3 Supply Chain Operations - ICLT Program
Lesson notes of climatology university.
Microbial diseases, their pathogenesis and prophylaxis
Complications of Minimal Access Surgery at WLH
Sports Quiz easy sports quiz sports quiz
Abdominal Access Techniques with Prof. Dr. R K Mishra
STATICS OF THE RIGID BODIES Hibbelers.pdf
RMMM.pdf make it easy to upload and study
O5-L3 Freight Transport Ops (International) V1.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Renaissance Architecture: A Journey from Faith to Humanism
2.FourierTransform-ShortQuestionswithAnswers.pdf
01-Introduction-to-Information-Management.pdf
Cell Types and Its function , kingdom of life
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Supply Chain Operations Speaking Notes -ICLT Program
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
master seminar digital applications in india

Cakephp tutorial

  • 2. CakePHP i AbouttheTutorial CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on an MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers guarantee a strict but natural separation of business logic from data and presentation layers. Audience This tutorial is meant for web developers and students who would like to learn how to develop websites using CakePHP. It will provide a good understanding of how to use this framework. Prerequisites Before you proceed with this tutorial, we assume that you have knowledge of HTML, Core PHP, and Advance PHP. We have used CakePHP version 3.2.7 in all the examples. Copyright&Disclaimer  Copyright 2016 by Tutorials Point (I) Pvt. Ltd. All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher. We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at contact@tutorialspoint.com
  • 3. CakePHP ii TableofContents About the Tutorial..................................................................................................................................i Audience ................................................................................................................................................i Prerequisites ..........................................................................................................................................i Copyright & Disclaimer...........................................................................................................................i Table of Contents ..................................................................................................................................ii 1. CAKEPHP — OVERVIEW .....................................................................................................1 CakePHP Request Cycle .........................................................................................................................1 2. CAKEPHP — INSTALLATION................................................................................................3 3. CAKEPHP — FOLDER STRUCTURE ......................................................................................4 4. CAKEPHP — CONFIGURATION ...........................................................................................6 General Configuration ...........................................................................................................................6 Databases Configuration .......................................................................................................................7 5. CAKEPHP — EMAIL CONFIGURATION ................................................................................9 6. CAKEPHP — ROUTING......................................................................................................11 Connecting Routes...............................................................................................................................11 Passed Arguments...............................................................................................................................13 7. CAKEPHP — GENERATING URLS.......................................................................................16 8. CAKEPHP — REDIRECT ROUTING .....................................................................................18 9. CAKEPHP — CONTROLLERS..............................................................................................20 AppController......................................................................................................................................20 Controller Actions................................................................................................................................21
  • 4. CakePHP iii Redirecting ..........................................................................................................................................21 Loading Models ...................................................................................................................................24 10. CAKEPHP — VIEWS ..........................................................................................................25 View Templates...................................................................................................................................25 View Variables.....................................................................................................................................25 11. CAKEPHP — EXTENDING VIEWS.......................................................................................28 12. CAKEPHP ─ VIEW ELEMENTS............................................................................................30 13. CAKEPHP ─ VIEW EVENTS.................................................................................................33 14. CAKEPHP — WORKING WITH DATABASE .........................................................................34 Insert a Record ....................................................................................................................................34 15. CAKEPHP ─ VIEW A RECORD ............................................................................................37 16. CAKEPHP — UPDATE A RECORD.......................................................................................40 17. CAKEPHP ─ DELETE A RECORD .........................................................................................44 18. CAKEPHP — SERVICES......................................................................................................47 Authentication ....................................................................................................................................47 19. CAKEPHP — ERRORS & EXCEPTION HANDLING................................................................52 Errors and Exception Configuration .....................................................................................................52 20. CAKEPHP — LOGGING .....................................................................................................55 21. CAKEPHP — FORM HANDLING.........................................................................................59 22. CAKEPHP — INTERNATIONALIZATION..............................................................................65 Email ...................................................................................................................................................68
  • 5. CakePHP iv 23. CAKEPHP — SESSION MANAGEMENT..............................................................................73 Accessing Session Object .....................................................................................................................73 Writing Session Data ...........................................................................................................................73 Reading Session Data ..........................................................................................................................73 Delete Session Data.............................................................................................................................74 Destroying a Session............................................................................................................................74 Renew a Session..................................................................................................................................75 Complete Session ................................................................................................................................75 24. CAKEPHP — COOKIE MANAGEMENT ...............................................................................80 Write Cookie........................................................................................................................................80 Read Cookie ........................................................................................................................................80 Check Cookie .......................................................................................................................................80 Delete Cookie ......................................................................................................................................81 25. CAKEPHP — SECURITY .....................................................................................................86 Encryption and Decryption ..................................................................................................................86 CSRF ....................................................................................................................................................86 Security Component............................................................................................................................87 26. CAKEPHP — VALIDATION.................................................................................................90 Validation Methods.............................................................................................................................90 27. CAKEPHP — CREATING VALIDATORS................................................................................93 Validating Data....................................................................................................................................93
  • 6. CakePHP 5 CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has number of libraries to reduce the overload of most common tasks. Following are the advantages of using CakePHP.  Open Source  MVC Framework  Templating Engine  Caching Operations  Search Engine Friendly URLs  Easy CRUD (Create, Read, Update, Delete) Database Interactions.  Libraries and Helpers  Built-in Validation  Localization  Email, Cookie, Security, Session, and Request Handling Components  View Helpers for AJAX, JavaScript, HTML Forms and More CakePHPRequestCycle The following illustration describes how a Request Lifecycle works: 1. CakePHP — Overview
  • 7. CakePHP 6 A typical CakePHP request cycle starts with a user requesting a page or resource in your application. At a high level, each request goes through the following steps:  The webserver rewrite rules direct the request to webroot/index.php.  Your application’s autoloader and bootstrap files are executed.  Any dispatch filters that are configured can handle the request, and optionally generate a response.  The dispatcher selects the appropriate controller & action based on routing rules.  The controller’s action is called and the controller interacts with the required Models and Components.  The controller delegates response creation to the View to generate the output resulting from the model data.  The view uses Helpers and Cells to generate the response body and headers.  The response is sent back to the client.
  • 8. CakePHP 7 Installing CakePHP is simple and easy. You can install it from composer or you can download it from github — https://github.com/cakephp/cakephp/releases. We will further understand how to install CakePHP in WampServer. After downloading it from github, extract all the files in a folder called “CakePHP” in WampServer. You can give custom name to folder but we have used “CakePHP”. Make sure that the directories logs, tmp and all its subdirectories have write permission as CakePHP uses these directories for various operations. After extracting it, let’s check whether it has been installed correctly or not by visiting the following URL in browser: http://localhost:85/CakePHP/ The above URL will direct you to the screen as shown below. This shows that CakePHP has successfully been installed. 2. CakePHP – Installation
  • 9. CakePHP 8 Take a look at the following screenshot. It shows the folder structure of CakePHP. The following table describes the role of each folder: Folder Name Description bin The bin folder holds the Cake console executables. config The config folder holds the (few) configuration files CakePHP uses. Database connection details, bootstrapping, core configuration files and more should be stored here. logs The logs folder normally contains your log files, depending on your log configuration. plugins The plugins folder is where the Plugins your application uses are stored. src The src folder will be where you work your magic: It is where your application’s files will be placed. CakePHP’s src folder is where you will do most of your application development. Let’s look a little closer at the folders inside src.  Console Contains the console commands and console tasks for your application.  Controller Contains your application’s controllers and their components. 3. CakePHP — Folder Structure
  • 10. CakePHP 9  Locale Stores string files for internationalization.  Model Contains your application’s tables, entities and behaviors.  View Presentational classes are placed here: cells, helpers, and template files.  Template Presentational files are placed here: elements, error pages, layouts, and view template files. tests The tests folder will be where you put the test cases for your application. tmp The tmp folder is where CakePHP stores temporary data. The actual data it stores depends on how you have CakePHP configured, but this folder is usually used to store model descriptions and sometimes session information. vendor The vendor folder is where CakePHP and other application dependencies will be installed. Make a personal commitment not to edit files in this folder. We can’t help you if you’ve modified the core. webroot The webroot directory is the public document root of your application. It contains all the files you want to be publically reachable.
  • 11. CakePHP 10 CakePHP comes with one configuration file by default and we can modify it according to our needs. There is one dedicated folder “config” for this purpose. CakePHP comes with different configuration options. GeneralConfiguration The following table describes the role of various variables and how they affect your CakePHP application. Variable Name Description debug Changes CakePHP debugging output. false = Production mode. No error messages, errors, or warnings shown. true = Errors and warnings shown. App.namespace The namespace to find app classes under. App.baseUrl Un-comment this definition if you don’t plan to use Apache’s mod_rewrite with CakePHP. Don’t forget to remove your .htaccess files too. App.base The base directory the app resides in. If false, this will be auto detected. App.encoding Define what encoding your application uses. This encoding is used to generate the charset in the layout, and encode entities. It should match the encoding values specified for your database. App.webroot The webroot directory. App.wwwRoot The file path to webroot. App.fullBaseUrl The fully qualified domain name (including protocol) to your application’s root. App.imageBaseUrl Web path to the public images directory under webroot. App.cssBaseUrl Web path to the public css directory under webroot. App.jsBaseUrl Web path to the public js directory under webroot. App.paths Configure paths for non-class based resources. Supports the plugins, templates, locales subkeys, which allow the definition of paths for plugins, view templates and locale files respectively. Security.salt A random string used in hashing. This value is also used as the HMAC salt when doing symmetric encryption. Asset.timestamp Appends a timestamp which is last modified time of the particular file at the end of asset files URLs (CSS, JavaScript, Image) when using proper helpers. Valid values:  (bool) false - Doesn’t do anything (default)  (bool) true - Appends the timestamp when debug is true 4. CakePHP – Configuration
  • 12. CakePHP 11  (string) ‘force’ - Always appends the timestamp DatabasesConfiguration Database can be configured in config/app.php file. This file contains a default connection with provided parameters which can be modified as per our choice. The below screenshot shows the default parameters and values which should be modified as per the requirement. Let’s understand each parameter in detail: Key Description className The fully namespaced class name of the class that represents the connection to a database server. This class is responsible for loading the database driver, providing SQL transaction mechanisms and preparing SQL statements among other things. driver The class name of the driver used to implements all specificities for a database engine. This can either be a short classname using plugin syntax, a fully namespaced name, or a constructed driver instance. Examples of short classnames are Mysql, Sqlite, Postgres, and Sqlserver. persistent Whether or not to use a persistent connection to the database. host The database server’s hostname (or IP address). username Database username password Database password
  • 13. CakePHP 12 database Name of Database port (optional) The TCP port or Unix socket used to connect to the server. encoding Indicates the character set to use when sending SQL statements to the server like ‘utf8’ etc. timezone Server timezone to set. schema Used in PostgreSQL database setups to specify which schema to use. unix_socket Used by drivers that support it to connect via Unix socket files. If you are using PostgreSQL and want to use Unix sockets, leave the host key blank. ssl_key The file path to the SSL key file. (Only supported by MySQL). ssl_cert The file path to the SSL certificate file. (Only supported by MySQL). ssl_ca The file path to the SSL certificate authority. (Only supported by MySQL). init A list of queries that should be sent to the database server as when the connection is created. log Set to true to enable query logging. When enabled queries will be logged at a debug level with the queriesLog scope. quoteIdentifiers Set to true if you are using reserved words or special characters in your table or column names. Enabling this setting will result in queries built using the Query Builder having identifiers quoted when creating SQL. It decreases performance. flags An associative array of PDO constants that should be passed to the underlying PDO instance. cacheMetadata Either boolean true, or a string containing the cache configuration to store meta data in. Having metadata caching disable is not advised and can result in very poor performance.
  • 14. CakePHP 13 Email can be configured in file config/app.php. It is not required to define email configuration in config/app.php. Email can be used without it; just use the respective methods to set all configurations separately or load an array of configs. Configuration for Email defaults is created using config() and configTransport(). Email Configuration Transport By defining transports separately from delivery profiles, you can easily re-use transport configuration across multiple profiles. You can specify multiple configurations for production, development and testing. Each transport needs a className. Valid options are as follows:  Mail — Send using PHP mail function   Smtp — Send using SMTP   Debug — Do not send the email, just return the result You can add custom transports (or override existing transports) by adding the appropriate file to src/Mailer/Transport. Transports should be named YourTransport.php, where 'Your' is the name of the transport. Following is the example of Email configuration transport. Example 'EmailTransport' => [ 'default' => [ 'className' => 'Mail', // The following keys are used in SMTP transports 'host' => 'localhost', 'port' => 25, 'timeout' => 30, 'username' => 'user', 'password' => 'secret', 'client' => null, 'tls' => null, 'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null), ], ], 5. CakePHP – Email Configuration
  • 15. CakePHP 14 Email Delivery Profiles Delivery profiles allow you to predefine various properties about email messages from your application and give the settings a name. This saves duplication across your application and makes maintenance and development easier. Each profile accepts a number of keys. Following is an example of Email delivery profiles. Example 'Email' => [ 'default' => [ 'transport' => 'default', 'from' => 'you@localhost', ], ],
  • 16. CakePHP 15 End of ebook preview If you liked what you saw… Buy it from our store @ https://store.tutorialspoint.com