CakePHP 是一个开源 MVC 框架。它使开发、部署和维护应用程序变得更加容易。 CakePHP 有许多库可以减少大多数常见任务的过载。
使用 CakePHP 的优点如下 -
开源
MVC 框架
模板引擎
缓存操作
搜索引擎友好的网址
轻松的 CRUD(创建、读取、更新、删除)数据库交互。
图书馆和助手
内置验证
本地化
电子邮件、CakePHP 快速指南、安全性、会话和请求处理组件
查看 AJAX、JavaScript、HTML 表单等的帮助程序
下图描述了 CakePHP 中请求生命周期的工作原理 -
典型的 CakePHP 请求周期从用户请求应用程序中的页面或资源开始。在高层,每个请求都会经历以下步骤 -
网络服务器重写规则将请求定向到 webroot / index.php。
应用程序的自动加载器和引导文件已执行。
配置的任何调度过滤器都可以处理请求,并可以选择生成响应。
调度程序根据路由规则选择适当的控制器和操作。
调用控制器的操作,控制器与所需的模型和组件交互。
控制器将响应创建委托给视图以生成模型数据的输出。
视图使用 Helpers 和 Cells 生成响应正文和标头。
响应被发送回客户端。
在本章中,我们将展示 CakePHP 4.0.3 的安装。我们需要安装的最低 PHP 版本是 PHP 7.3.
在开始安装cakePHP之前,您需要安装PHP 7.3和Composer。
对于Windows用户,安装或更新PHP版本> 7.3的WAMP服务器。
前往 www.wampserver.com/en/download-wampserver-64bits/ 并安装它。
对于Linux用户,请参考TutorialsPoint网站,网址为www.tutorialspoint.com/php7/php7_installation_linux.htm来安装PHP。
转到 https://getcomposer.org/download/ 上的 Composer,然后根据您计算机的操作系统 (OS) 单击“下载”,然后在您的系统上安装 Composer。将位置添加到 Windows 用户的 PATH 变量中,以便您可以从任何目录使用 Composer。
安装完 Composer 后,现在让我们开始安装 CakePHP。
Windows用户进入wamp所在文件夹,在www/文件夹中创建一个文件夹cakephp4/.
对于 Linux 用户,创建文件夹 var/www/html/,然后创建文件夹 cakephp4/.
cakephp4/ 是我们要安装 CakePHP 的文件夹。
使用composer执行以下命令 -
composer create-project --prefer-dist cakephp/app:4.0.3 cakephp4
这是命令执行时您应该看到的内容 -
安装完成后,使用 localhost 在浏览器中打开您的项目。
相同的路径是http://localhost/cakephp。
在这里,我们将了解 CakePHP 中的文件夹结构和命名约定。让我们从了解文件夹结构开始。
看看下面的截图。它显示了 CakePHP 的文件夹结构。
下表描述了CakePHP中每个文件夹的作用 -
先生不 | 文件夹名称和说明 |
---|---|
1 |
bin bin 文件夹包含 Cake 控制台可执行文件。 |
2 |
配置 config 文件夹包含 CakePHP 使用的(几个)配置文件。数据库连接详细信息、引导、核心配置文件等应存储在此处。 |
3 |
日志 logs 文件夹通常包含您的日志文件,具体取决于您的日志配置。 |
4 |
插件 plugins 文件夹是存储应用程序使用的插件的位置。 |
5 |
资源 各个语言环境文件夹中的国际化文件将存储在此处。例如。 locales/en_US。 |
6 |
src src 文件夹将是你施展魔法的地方。您的应用程序文件将放置在此处,您将完成大部分应用程序开发。让我们仔细看看 src 中的文件夹。
|
7 |
模板 模板展示文件放置在这里:元素、错误页面、布局和视图模板文件。 |
8 |
测试 tests 文件夹将是您放置应用程序测试用例的位置。 |
9 |
tmp tmp文件夹是CakePHP存储临时数据的地方。它存储的实际数据取决于您如何配置 CakePHP,但此文件夹通常用于存储模型描述,有时还用于存储会话信息。 |
10 |
供应商 vendor 文件夹是 CakePHP 和其他应用程序依赖项的安装位置。做出个人承诺不编辑此文件夹中的文件。如果您修改了核心,我们无法帮助您。 |
11 |
webroot webroot 目录是您的应用程序的公共文档根目录。它包含您希望公开访问的所有文件。 |
Naming convention is not something mandatory to be followed, but is a good coding practice and will be very helpful as your project goes big.
The controller class name has to be plural, PascalCased and the name has to end with CakePHP 快速指南. For example, for Students class the name of the controller can be StudentsCakePHP 快速指南. Public methods on CakePHP 快速指南s are often exposed as ‘actions’ accessible through a web browser.
For example, the /users /view maps to the view() method of the UsersCakePHP 快速指南 out of the box. Protected or private methods cannot be accessed with routing.
Mostly, we have seen that our class name file name is almost the same. This is similar in cakephp.
For example, the class StudentsCakePHP 快速指南 will have the file named as StudentsCakePHP 快速指南.php. The files have to be saved as the module name and in the respective folders in app folder.
The tables used for CakePHP models, mostly have names plural with underscore.
For example, student_details, student_marks. The field name has an underscore, if it is made up of two words, for example, first_name, last_name.
For model, the classes are named as per database table, the names are plural, PascalCased and suffixed with Table.
For example, StudentDetailsTable, StudentMarksTable
For view templates, the files are based on controller functions.
For example, if the class StudentDetailsCakePHP 快速指南 has function showAll(), the view template will be named as show_all.php and saved inside template/yrmodule/show_all.php.
In this chapter, we will understand the Environment CakePHP 快速指南, General Configuration, Database Configuration and Email Configuration in CakePHP.
Configuration 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.
Let us start by understanding the Environment CakePHP 快速指南 in CakePHP.
Environment variables make the working of your application on different environments easy. For example, on dev server, test server, staging server and production server environment. For all these environments, you can make use of env() function to read the configuration for the environment you need and build your application.
In your config folder, you will come across config/.env.example. This file has all the variables that will be changed based on your environment. To start with, you can create a file in config folder i.e. config/.env and define those variables and use them. In case you need any additional variables, it can go in that file.
You can read your environment variable using env() function as shown below −
$debug = env('APP_DEBUG', false);
The first one is the name of the environment variable you want and second value is the default value. The default value is used, if there is no value found for the environment variable.
The following table describes the role of various variables and how they affect your CakePHP application.
Sr.No | Variable CakePHP 快速指南 & Description |
---|---|
1 |
debug Changes CakePHP debugging output. false = Production mode. No error messages, errors, or warnings shown. true = Errors and warnings shown. |
2 |
App.namespace The namespace to find app classes under. |
3 |
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. |
4 |
App.base The base directory the app resides in. If false, this will be auto detected. |
5 |
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. |
6 |
App.webroot The webroot directory. |
7 |
App.wwwRoot The file path to webroot. |
8 |
App.fullBaseUrl The fully qualified domain name (including protocol) to your application’s root. |
9 |
App.imageBaseUrl Web path to the public images directory under webroot. |
10 |
App.cssBaseUrl Web path to the public css directory under webroot. |
11 |
App.jsBaseUrl Web path to the public js directory under webroot. |
12 |
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. |
13 |
Security.salt A random string used in hashing. This value is also used as the HMAC salt when doing symmetric encryption. |
14 |
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. The valid values are −
|
Database can be configured in config/app.php and config/app_local.php file. This file contains a default connection with provided parameters, which can be modified as per our choice.
The below snippet shows the default parameters and values, which should be modified as per the requirement.
*/ 'Datasources' => [ 'default' => [ 'host' => 'localhost', 'username' => 'my_app', 'password' => 'secret', 'database' => 'my_app', 'url' => env('DATABASE_URL', null), ], /* * The test connection is used during the test suite. */ 'test' => [ 'host' => 'localhost', //'port' => 'non_standard_port_number', 'username' => 'my_app', 'password' => 'secret', 'database' => 'test_myapp', //'schema' => 'myapp', ], ],
Let us understand each parameter in detail in config/app_local.php.
Host | The database server’s hostname (or IP address). |
---|---|
username | Database username |
password | Database password. |
database | CakePHP 快速指南 of Database. |
Port | The TCP port or Unix socket used to connect to the server. |
'Datasources' => [ 'default' => [ 'classCakePHP 快速指南' => Connection::class, 'driver' => Mysql::class, 'persistent' => false, 'timezone' => 'UTC', //'encoding' => 'utf8mb4', 'flags' => [], 'cacheMetadata' => true, 'log' => false, 'quoteIdentifiers' => false, //'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'], ], ]
Let us understand each parameter in detail in config/app.php.
Sr.No | Key & Description |
---|---|
1 |
classCakePHP 快速指南 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. |
2 |
driver The class name of the driver used to implement 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. |
3 |
persistent Whether or not to use a persistent connection to the database. |
4 |
encoding Indicates the character set to use, when sending SQL statements to the server like ‘utf8’ etc. |
5 |
timezone Server timezone to set. |
6 |
init A list of queries that should be sent to the database server as and when the connection is created. |
7 | log
log Set to true to enable query logging. When enabled queries will be logged at a debug level with the queriesLog scope. |
8 |
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. |
9 |
flags An associative array of PDO constants that should be passed to the underlying PDO instance. |
10 |
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. |
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().
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 classCakePHP 快速指南. 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.
'EmailTransport' => [ 'default' => [ 'classCakePHP 快速指南' => '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), ], ],
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.
'Email' => [ 'default' => [ 'transport' => 'default', 'from' => 'you@localhost', ], ],
In this chapter, we are going to learn the following topics related to routing −
In this section, we will see how you can implement routes, how you can pass arguments from URL to controller’s action, how you can generate URLs, and how you can redirect to a specific URL. Normally, routes are implemented in file config/routes.php. Routing can be implemented in two ways −
Here, is an example presenting both the types.
// Using the scoped route builder. Router::scope('/', function ($routes) { $routes->connect('/', ['controller' => 'CakePHP 快速指南s', 'action' => 'index']); }); // Using the static method. Router::connect('/', ['controller' => 'CakePHP 快速指南s', 'action' => 'index']);
Both the methods will execute the index method of CakePHP 快速指南sCakePHP 快速指南. Out of the two methods, scoped route builder gives better performance.
Router::connect() method is used to connect routes. The following is the syntax of the method −
static Cake\Routing\Router::connect($route, $defaults =[], $options =[])
There are three arguments to the Router::connect() method −
The first argument is for the URL template you wish to match.
The second argument contains default values for your route elements.
The third argument contains options for the route, which generally contains regular expression rules.
Here, is the basic format of a route −
$routes->connect( 'URL template', ['default' => 'defaultValue'], ['option' => 'matchingRegex'] );
Make changes in the config/routes.php file as shown below.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { // Register scoped middleware for in scopes. $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); $builder->connect('/', ['controller' => 'Tests', 'action' => 'show']); $builder->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']); $builder->fallbacks(); });
Create a TestsCakePHP 快速指南.php file at src/CakePHP 快速指南/TestsCakePHP 快速指南.php. Copy the following code in the controller file.
src/CakePHP 快速指南/TestsCakePHP 快速指南.php
<?php declare(strict_types=1); namespace App\CakePHP 快速指南; use Cake\Core\Configure; use Cake\Http\Exception\ForbiddenException; use Cake\Http\Exception\NotFoundException; use Cake\Http\Response; use Cake\View\Exception\MissingTemplateException; class TestsCakePHP 快速指南 extends AppCakePHP 快速指南 { public function show() { } }
Create a folder Tests under src/Template and under that folder, create a View file called show.php. Copy the following code in that file.
src/Template/Tests/show.php
<h1>This is CakePHP tutorial and this is an example of connecting routes.</h1>
Execute the above example by visiting the following URL which is available at http://localhost/cakephp4/
The above URL will yield the following output.
Passed arguments are the arguments which are passed in the URL. These arguments can be passed to controller’s action. These passed arguments are given to your controller in three ways.
Following example shows, how we can pass arguments to the action of the controller. Visit the following URL at http://localhost/cakephp4/tests/value1/value2
This will match the following route line.
$builder->connect('tests/:arg1/:arg2', ['controller' => 'Tests', 'action' => 'show'],['pass' => ['arg1', 'arg2']]);
Here, the value1 from URL will be assigned to arg1 and value2 will be assigned to arg2.
Once the argument is passed to the controller’s action, you can get the argument with the following statement.
$args = $this->request->params[‘pass’]
The arguments passed to controller’s action will be stored in $args variable.
The argument can also be passed to action by the following statement −
$routes->connect('/', ['controller' => 'Tests', 'action' => 'show',5,6]);
The above statement will pass two arguments 5, and 6 to TestCakePHP 快速指南’s show() method.
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { // Register scoped middleware for in scopes. $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); $builder->connect('tests/:arg1/:arg2', ['controller' => 'Tests', 'action' => 'show'],['pass' => ['arg1', 'arg2']]); $builder->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']); $builder->fallbacks(); });
Create a TestsCakePHP 快速指南.php file at src/CakePHP 快速指南/TestsCakePHP 快速指南.php. Copy the following code in the controller file.
src/CakePHP 快速指南/TestsCakePHP 快速指南.php
<?php declare(strict_types=1); namespace App\CakePHP 快速指南; use Cake\Core\Configure; use Cake\Http\Exception\ForbiddenException; use Cake\Http\Exception\NotFoundException; use Cake\Http\Response; use Cake\View\Exception\MissingTemplateException; class TestsCakePHP 快速指南 extends AppCakePHP 快速指南 { public function show($arg1, $arg2) { $this->set('argument1',$arg1); $this->set('argument2',$arg2); } }
Create a folder Tests at src/Template and under that folder create a View file called show.php. Copy the following code in that file.
src/Template/Tests/show.php.
<h1>This is CakePHP tutorial and this is an example of Passed arguments.</h1> <?php echo "Argument-1:".$argument1."<br/>"; echo "Argument-2:".$argument2."<br>"; ?>
Execute the above example by visiting the following URL http://localhost/cakephp4/tests/CakePHP 快速指南/Kunal
Upon execution, the above URL will produce the following output.
This is a cool feature of CakePHP. Using the generated URLs, we can easily change the structure of URL in the application without modifying the whole code.
url( string|array|null $url null , boolean $full false )
The above function will take two arguments −
The first argument is an array specifying any of the following - 'controller', 'action', 'plugin'. Additionally, you can provide routed elements or query string parameters. If string, it can be given the name of any valid url string.
If true, the full base URL will be prepended to the result. Default is false.
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { // Register scoped middleware for in scopes. $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); $builder->connect('/generate',['controller'=>'Generates','action'=>'show']); $builder->fallbacks(); });
Create a GeneratesCakePHP 快速指南.php file at src/CakePHP 快速指南/GeneratesCakePHP 快速指南.php. Copy the following code in the controller file.
src/CakePHP 快速指南/GeneratesCakePHP 快速指南.php
<?php declare(strict_types=1); namespace App\CakePHP 快速指南; 21 use Cake\Core\Configure; use Cake\Http\Exception\ForbiddenException; use Cake\Http\Exception\NotFoundException; use Cake\Http\Response; use Cake\View\Exception\MissingTemplateException; class GeneratesCakePHP 快速指南 extends AppCakePHP 快速指南 { public function show() { } }
Create a folder Generates at src/Template and under that folder, create a View file called show.php. Copy the following code in that file.
src/Template/Generates/show.php
<h1>This is CakePHP tutorial and this is an example of Generating URLs<h1> </h1> </h1>
Execute the above example by visiting the following URL −
http://localhost/cakephp4/generate
The above URL will produce the following output −
CakePHP 快速指南 routing is useful, when we want to inform client applications that, this URL has been moved. The URL can be redirected using the following function −
static Cake\Routing\Router::redirect($route, $url, $options =[])
There are three arguments to the above function as follows −
A string describing the template of the route.
A URL to redirect to.
An array matching the named elements in the route to regular expressions which that element should match.
Make Changes in the config/routes.php file as shown below. Here, we have used controllers that were created previously.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { // Register scoped middleware for in scopes. $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); $builder->connect('/generate',['controller'=>'Generates','action'=>'show']); $builder->redirect('/redirect','https://tutorialspoint.com/'); $builder->fallbacks(); });
Execute the above example by visiting the following URLs.
URL 1 − http://localhost/cakephp4/generate
URL 2 − http://localhost/cakephp4/redirect
You will be redirected to https://tutorialspoint.com
The controller as the name indicates controls the application. It acts like a bridge between models and views. CakePHP 快速指南s handle request data, makes sure that correct models are called and right response or view is rendered.
Methods in the controllers’ class are called actions. Each controller follows naming conventions. The CakePHP 快速指南 class names are in plural form, Camel Cased, and end in CakePHP 快速指南 — PostsCakePHP 快速指南.
The AppConttroller class is the parent class of all applications’ controllers. This class extends the CakePHP 快速指南 class of CakePHP. AppCakePHP 快速指南 is defined at src/CakePHP 快速指南/AppCakePHP 快速指南.php. The file contains the following code.
<?php declare(strict_types=1); namespace App\CakePHP 快速指南; use Cake\CakePHP 快速指南\CakePHP 快速指南; class AppCakePHP 快速指南 extends CakePHP 快速指南 { public function initialize(): void { parent::initialize(); $this->loadComponent('RequestHandler'); $this->loadComponent('Flash'); } }
AppCakePHP 快速指南 can be used to load components that will be used in every controller of your application. The attributes and methods created in AppCakePHP 快速指南 will be available in all controllers that extend it. The initialize() method will be invoked at the end of controller’s constructor to load components.
The methods in the controller class are called Actions. These actions are responsible for sending appropriate response for browser/user making the request. View is rendered by the name of action, i.e., the name of method in controller.
class RecipesCakePHP 快速指南 extends AppCakePHP 快速指南 { public function view($id) { // Action logic goes here. } public function share($customerId, $recipeId) { // Action logic goes here. } public function search($query) { // Action logic goes here. } }
As you can see in the above example, the RecipesCakePHP 快速指南 has 3 actions − View, Share, and Search.
For redirecting a user to another action of the same controller, we can use the setAction() method. The following is the syntax for the setAction() method.
Cake\CakePHP 快速指南\CakePHP 快速指南::setAction($action, $args...)
The following code will redirect the user to index action of the same controller.
$this->setAction('index');
The following example shows the usage of the above method.
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { // Register scoped middleware for in scopes. $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); $builder->connect('/redirect-controller',['controller'=>'CakePHP 快速指南s','action'=>'action1']); $builder->connect('/redirect-controller2',['controller'=>'CakePHP 快速指南s','action'=>'action2']); $builder->fallbacks(); });
Create a CakePHP 快速指南sCakePHP 快速指南.php file at src/CakePHP 快速指南/CakePHP 快速指南sCakePHP 快速指南.php. Copy the following code in the controller file.
src/CakePHP 快速指南/CakePHP 快速指南sCakePHP 快速指南.php
<?php declare(strict_types=1); namespace App\CakePHP 快速指南; use Cake\Core\Configure; use Cake\Http\Exception\ForbiddenException; use Cake\Http\Exception\NotFoundException; use Cake\Http\Response; use Cake\View\Exception\MissingTemplateException; class CakePHP 快速指南sCakePHP 快速指南 extends AppCakePHP 快速指南 { public function action1() { } public function action2(){ echo "redirecting from action2"; $this->setAction('action1'); } }
Create a directory CakePHP 快速指南s at src/Template and under that directory create a View file called action1.php. Copy the following code in that file.
src/Template/CakePHP 快速指南s/action1.php
<h1>This is an example of how to redirect within controller.</h1>
Execute the above example by visiting the following URL.
http://localhost/cakephp4/redirect-controller
Upon execution, you will receive the following output.
Now, visit the following URL: http://localhost/cakephp4/redirect-controller2
The above URL will give you the following output.
In CakePHP, a model can be loaded using the loadModel() method. The following is the syntax for the loadModel() method −
Cake\CakePHP 快速指南\CakePHP 快速指南::loadModel(string $modelClass, string $type)
There are two arguments to the above function as follows −
The first argument is the name of model class.
The second argument is the type of repository to load.
If you want to load CakePHP 快速指南s model in a controller, then it can be loaded by writing the following line in controller’s action.
$this->loadModel('CakePHP 快速指南s');
The letter “V” in the MVC is for Views. Views are responsible for sending output to user based on request. View Classes is a powerful way to speed up the development process.
The View Templates file of CakePHP gets data from controller and then render the output so that it can be displayed properly to the user. We can use variables, various control structures in template.
Template files are stored in src/Template/, in a directory named after the controller that uses the files, and named after the action it corresponds to. For example, the Viewfile for the Products controller’s “view()” action, would normally be found in src/Template/Products/view.php.
In short, the name of the controller (ProductsCakePHP 快速指南) is same as the name of the folder (Products) but without the word CakePHP 快速指南 and name of action/method (view()) of the controller (ProductsCakePHP 快速指南) is same as the name of the View file(view.php).
View variables are variables which get the value from controller. We can use as many variables in view templates as we want. We can use the set() method to pass values to variables in views. These set variables will be available in both the view and the layout your action renders. The following is the syntax of the set() method.
Cake\View\View::set(string $var, mixed $value)
This method takes two arguments − the name of the variable and its value.
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { // Register scoped middleware for in scopes. $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); $builder->connect('template',['controller'=>'Products','action'=>'view']); $builder->fallbacks(); });
Create a ProductsCakePHP 快速指南.php file at src/CakePHP 快速指南/ProductsCakePHP 快速指南.php. Copy the following code in the controller file.
src/CakePHP 快速指南/ProductsCakePHP 快速指南.php
<?php declare(strict_types=1); namespace App\CakePHP 快速指南; use Cake\Core\Configure; use Cake\Http\Exception\ForbiddenException; use Cake\Http\Exception\NotFoundException; use Cake\Http\Response; use Cake\View\Exception\MissingTemplateException; class ProductsCakePHP 快速指南 extends AppCakePHP 快速指南 { public function view(){ $this->set('Product_CakePHP 快速指南','XYZ'); } }
Create a directory Products at src/Template and under that folder create a View file called view.php. Copy the following code in that file.
Value of variable is: <?php echo $Product_CakePHP 快速指南; ? >
Execute the above example by visiting the following URL.
http://localhost/cakephp4/template
The above URL will produce the following output.
Many times, while making web pages, we want to repeat certain part of pages in other pages. CakePHP has such facility by which one can extend view in another view and for this, we need not repeat the code again.
The extend() method is used to extend views in View file. This method takes one argument, i.e., the name of the view file with path. Don’t use extension .ctp while providing the name of the View file.
Make changes in the config/routes.php file as shown in the following program.
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); $builder->connect('extend',['controller'=>'Extends','action'=>'index']); $builder->fallbacks(); });
Create an ExtendsCakePHP 快速指南.php file at src/CakePHP 快速指南/ExtendsCakePHP 快速指南.php. Copy the following code in the controller file.
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; class ExtendsCakePHP 快速指南 extends AppCakePHP 快速指南{ public function index(){ } } ?>
Create a directory Extends at src/Template and under that folder create a View file called header.php. Copy the following code in that file.
<div align="center"> <h1>Common Header</h1> </div> = $this->fetch('content') ?>
Create another View under Extends directory called index.php. Copy the following code in that file. Here, we are extending the above view header.php.
<?php $this->extend('header'); ?> This is an example of extending view.
Execute the above example by visiting the following URL http://localhost/cakephp4/extend
Upon execution, you will receive the following output.
Certain parts of the web pages are repeated on multiple web pages, but at different locations. CakePHP can help us reuse these repeated parts. These reusable parts are called Elements - help box, extra menu, etc. An element is basically a mini-view. We can also pass variables in elements.
Cake\View\View::element(string $elementPath, array $data, array $options =[]
There are three arguments to the above function as follows −
The first argument is the name of the template file in the /src/Template/element/ folder.
The second argument is the array of data to be made available to the rendered view.
The third argument is for the array of options. e.g. cache.
Out of the 3 arguments, the first one is compulsory, while the rest are optional.
Create an element file at src/Template/element directory called helloworld.php. Copy the following code in that file.
<p>Hello World</p>
Create a folder Elems at src/Template and under that directory create a View file called index.php. Copy the following code in that file.
Element Example: <?php echo $this->element('helloworld'); ?>
Make Changes in the config/routes.php file as shown in the following program.
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); $builder->connect('/element-example',['controller'=>'Elems','action'=>'index']); $builder->fallbacks(); });
Create an ElemsCakePHP 快速指南.php file at src/CakePHP 快速指南/ElemsCakePHP 快速指南.php. Copy the following code in the controller file.
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; class ElemsCakePHP 快速指南 extends AppCakePHP 快速指南{ public function index(){ } } ?>
Execute the above example by visiting the following URL http://localhost/cakephp4/element-example
Upon execution, the above URL will give you the following output.
There are several callbacks/events that we can use with View Events. These events are helpful to perform several tasks before something happens or after something happens. The following is a list of callbacks that can be used with CakePHP −
Sr.No | Event Function & Description |
---|---|
1 |
Helper::beforeRender(Event $event,$viewFile) The beforeRender method is called after the controller’s beforeRender method but before the controller renders view and layout. This receives the file being rendered as an argument. |
2 |
Helper::beforeRenderFile(Event $event, $viewFile) This method is called before each view file is rendered. This includes elements, views, parent views and layouts. |
3 |
Helper::afterRenderFile(Event $event, $viewFile, $content) This method is called after each View file is rendered. This includes elements, views, parent views and layouts. A callback can modify and return $content to change how the rendered content will be displayed in the browser. |
4 |
Helper::afterRender(Event $event, $viewFile) This method is called after the view has been rendered, but before the layout rendering has started. |
5 |
Helper::beforeLayout(Event $event, $layoutFile) This method is called before the layout rendering starts. This receives the layout filename as an argument. |
6 |
Helper::afterLayout(Event $event, $layoutFile) This method is called after the layout rendering is complete. This receives the layout filename as an argument. |
Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.
Further, we also need to configure our database in config/app_local.php file.
'Datasources' => [ 'default' => [ 'host' => 'localhost', 'username' => 'my_app', 'password' => 'secret', 'database' => 'my_app', 'url' => env('DATABASE_URL', null), ], /* * The test connection is used during the test suite. */ 'test' => [ 'host' => 'localhost', //'port' => 'non_standard_port_number', 'username' => 'my_app', 'password' => 'secret', 'database' => 'test_myapp', //'schema' => 'myapp', ], ],
The default connection has following details −
'host' => 'localhost', 'username' => 'my_app', 'password' => 'secret', 'database' => 'my_app',
You can change the details, i.e. host, username, password and database as per your choice.
Once done, make sure it is updated in config/app_local.php in Datasources object.
Now, we will continue with above details, go to your phpmyadmin or mysql database and create user my_app as shown below −
Give the necessary privileges and save it. Now, we have the database details as per the configuration mentioned in app_local.php. When you check CakePHP home page, this is what you should get −
Now, we will create the following users’ table in the database.
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `password` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1
To insert a record in database, we first need to get hold of a table using TableRegistry class. We can fetch the instance out of registry using get() method. The get() method will take the name of the database table as an argument.
This new instance is used to create new entity. Set necessary values with the instance of new entity. We now have to call the save() method with TableRegistry class’s instance which will insert new record in database.
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('/users/add', ['controller' => 'Users', 'action' => 'add']); $builder->fallbacks(); });
Create a UsersCakePHP 快速指南.php file at src/CakePHP 快速指南/UsersCakePHP 快速指南.php. Copy the following code in the controller file.
src/controller/UsersCakePHP 快速指南.php
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; use Cake\ORM\TableRegistry; use Cake\Datasource\ConnectionManager; use Cake\Auth\DefaultPasswordHasher; class UsersCakePHP 快速指南 extends AppCakePHP 快速指南{ public function add(){ if($this->request->is('post')){ $username = $this->request->getData('username'); $hashPswdObj = new DefaultPasswordHasher; $password = $hashPswdObj->hash($this->request->getData('password')); $users_table = TableRegistry::get('users'); $users = $users_table->newEntity($this->request->getData()); $users->username = $username; $users->password = $password; $this->set('users', $users); if($users_table->save($users)) echo "User is added."; } } } ?>
Create a directory Users at src/Template and under that directory create a View file called add.php. Copy the following code in that file.
src/Template/Users/add.php
<?php echo $this->Form->create(NULL,array('url'=>'/users/add')); echo $this->Form->control('username'); echo $this->Form->control('password'); echo $this->Form->button('Submit'); echo $this->Form->end(); ?>
Execute the above example by visiting the following URL. http://localhost/cakephp4/users/add
Upon execution, you will receive the following output.
The data will be saved in the users table as shown below −
To view records of database, we first need to get hold of a table using the TableRegistry class. We can fetch the instance out of registry using get() method. The get() method will take the name of the database table as argument.
Now, this new instance is used to find records from database using find() method. This method will return all records from the requested table.
Make changes in the config/routes.php file as shown in the following code.
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('/users', ['controller' => 'Users', 'action' => 'index']); $builder->fallbacks(); });
Create a UsersCakePHP 快速指南.php file at src/CakePHP 快速指南/UsersCakePHP 快速指南.php. Copy the following code in the controller file.
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; use Cake\ORM\TableRegistry; use Cake\Datasource\ConnectionManager; class UsersCakePHP 快速指南 extends AppCakePHP 快速指南{ public function index(){ $users = TableRegistry::get('users'); $query = $users->find(); $this->set('results',$query); } } ?>
Create a directory Users at src/Template, ignore if already created, and under that directory create a View file called index.php. Copy the following code in that file.
<a href="add">Add User</a>
ID | Username | Password | Edit | Delete | ".$row->id." | "; echo ""; echo " | ".$row->password." | "; echo "Edit | "; echo "Delete | "; endforeach; ?>
Execute the above example by visiting the following URL http://localhost/cakephp4/users
Upon execution, the above URL will give you the following output.
To update a record in database, we first need to get hold of a table using TableRegistry class. We can fetch the instance out of registry using the get() method. The get() method will take the name of the database table as an argument. Now, this new instance is used to get particular record that we want to update.
Call the get() method with this new instance, and pass the primary key to find a record, which will be saved in another instance. Use this instance, to set new values that you want to update and then, finally call the save() method with the TableRegistry class’s instance to update record.
Make changes in the config/routes.php file as shown in the following code.
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('/users/edit', ['controller' => 'Users', 'action' => 'edit']); $builder->fallbacks(); });
Create a UsersCakePHP 快速指南.php file at src/CakePHP 快速指南/UsersCakePHP 快速指南.php. Copy the following code in the controller file.
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; use Cake\ORM\TableRegistry; use Cake\Datasource\ConnectionManager; class UsersCakePHP 快速指南 extends AppCakePHP 快速指南{ public function index(){ $users = TableRegistry::get('users'); $query = $users->find(); $this->set('results',$query); } public function edit($id){ if($this->request->is('post')){ $username = $this->request->getData('username'); $password = $this->request->getData('password'); $users_table = TableRegistry::get('users'); $users = $users_table->get($id); $users->username = $username; $users->password = $password; if($users_table->save($users)) echo "User is udpated"; $this->setAction('index'); } else { $users_table = TableRegistry::get('users')->find(); $users = $users_table->where(['id'=>$id])->first(); $this->set('username',$users->username); $this->set('password',$users->password); $this->set('id',$id); } } } ?>
Create a directory Users at src/Template, ignore if already created, and under that directory create a view called index.php. Copy the following code in that file.
<a href="add">Add User</a>
ID | Username | Password | Edit | Delete | ".$row->id." | "; echo "".$row->username." | "; echo "".$row->password." | "; echo "Edit | "; echo "Delete | "; endforeach; ?>
Create another View file under the Users directory called edit.php and copy the following code in it.
<?php echo $this->Form->create(NULL,array('url'=>'/users/edit/'.$id)); echo $this->Form->control('username',['value'=>$username]); echo $this->Form->control('password',['value'=>$password]); echo $this->Form->button('Submit'); echo $this->Form->end(); ?>
Execute the above example by visiting the following URL and click on Edit link to edit record.
http://localhost/cakephp4/users
After visiting the above URL, it will display the records in users table as shown below −
Click on Edit button and it will display you following screen −
Now, we will update the name CakePHP 快速指南 to CakePHP 快速指南123 and submit the details. The next screen displayed will be as follows −
To delete a record in database, we first need to get hold of a table using the TableRegistry class. We can fetch the instance out of registry using the get() method. The get() method will take the name of the database table as an argument. Now, this new instance is used to get particular record that we want to delete.
Call the get() method with this new instance and pass the primary key to find a record which will be saved in another instance. Use the TableRegistry class’s instance to call the delete method to delete record from database.
Make changes in the config/routes.php file as shown in the following code.
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('/users/delete', ['controller' => 'Users', 'action' => 'delete']); $builder->fallbacks(); });
Create a UsersCakePHP 快速指南.php file at src/CakePHP 快速指南/UsersCakePHP 快速指南.php. Copy the following code in the controller file.
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; use Cake\ORM\TableRegistry; use Cake\Datasource\ConnectionManager; class UsersCakePHP 快速指南 extends AppCakePHP 快速指南{ public function index(){ $users = TableRegistry::get('users'); $query = $users->find(); $this->set('results',$query); } public function delete($id){ $users_table = TableRegistry::get('users'); $users = $users_table->get($id); $users_table->delete($users); echo "User deleted successfully."; $this->setAction('index'); } } ?>
Just create an empty View file under Users directory called delete.ctp.
Create a directory Users at src/Template, ignore if already created, and under that directory create a Viewfile called index.ctp. Copy the following code in that file.
<a href="add">Add User</a>
ID | Username | Password | Edit | Delete | ".$row->id." | "; echo "".$row->username." | "; echo "".$row->password." | "; echo "Edit | "; echo "Delete | "; endforeach; ?>
Execute the above example by visiting the following URL and click on Delete link to delete record.
http://localhost:85/CakePHP/users
After visiting the above URL and clicking on the Delete link, you will receive the following output where you can delete record.
Click on Delete link to delete the record.
This chapter deals with the information about the authentication process available in CakePHP.
CakePHP 快速指南 is the process of identifying the correct user. CakePHP supports three types of authentication.
FormAuthenticate − It allows you to authenticate users based on form POST data. Usually, this is a login form that users enter information into. This is default authentication method.
BasicAuthenticate − It allows you to authenticate users using Basic HTTP authentication
DigestAuthenticate − It allows you to authenticate users using Digest HTTP authentication.
Make changes in the config/routes.php file as shown in the following code.
config/routes.php
<?php use Cake\Core\Plugin; use Cake\Routing\RouteBuilder; use Cake\Routing\Router; Router::defaultRouteClass('DashedRoute'); Router::scope('/', function (RouteBuilder $routes) { $routes->connect('/auth',['controller'=>'Authexs','action'=>'index']); $routes->connect('/login',['controller'=>'Authexs','action'=>'login']); $routes->connect('/logout',['controller'=>'Authexs','action'=>'logout']); $routes->fallbacks('DashedRoute'); }); Plugin::routes();
Change the code of AppCakePHP 快速指南.php file as shown in the following program.
src/CakePHP 快速指南/AppCakePHP 快速指南.php
<?php namespace App\CakePHP 快速指南; use Cake\CakePHP 快速指南\CakePHP 快速指南; use Cake\Event\Event; use Cake\CakePHP 快速指南\Component\AuthComponent; class AppCakePHP 快速指南 extends CakePHP 快速指南 { public function initialize() { parent::initialize(); $this->loadComponent('RequestHandler'); $this->loadComponent('Flash'); $this->loadComponent('Auth', [ 'authenticate' => [ 'Form' => [ 'fields' => [ 'username' => 'username', 'password' => 'password' ] ] ], 'loginAction' => [ 'controller' => 'Authexs', 'action' => 'login' ], 'loginCakePHP 快速指南' => [ 'controller' => 'Authexs', 'action' => 'index' ], 'logoutCakePHP 快速指南' => [ 'controller' => 'Authexs', 'action' => 'login' ] ]); } public function beforeFilter(Event $event) { $this->Auth->allow(['index','view']); $this->set('loggedIn', $this->Auth->user()); } }
Create AuthexsCakePHP 快速指南.php file at src/CakePHP 快速指南/AuthexsCakePHP 快速指南.php. Copy the following code in the controller file.
src/CakePHP 快速指南/AuthexsCakePHP 快速指南.php
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; use Cake\ORM\TableRegistry; use Cake\Datasource\ConnectionManager; use Cake\Event\Event; use Cake\Auth\DefaultPasswordHasher; class AuthexsCakePHP 快速指南 extends AppCakePHP 快速指南 { var $components = array('Auth'); public function index(){ } public function login(){ if($this->request->is('post')) { $user = $this->Auth->identify(); if($user){ $this->Auth->setUser($user); return $this->redirect($this->Auth->redirectUrl()); } else $this->Flash->error('Your username or password is incorrect.'); } } public function logout(){ return $this->redirect($this->Auth->logout()); } } ?>
Create a directory Authexs at src/Template and under that directory create a View file called login.php. Copy the following code in that file.
src/Template/Authexs/login.php
<?php echo $this->Form->create(); echo $this->Form->control('username'); echo $this->Form->control('password'); echo $this->Form->button('Submit'); echo $this->Form->end(); ?>
Create another View file called logout.php. Copy the following code in that file.
src/Template/Authexs/logout.php
You are successfully logged out.
Create another View file called index.php. Copy the following code in that file.
src/Template/Authexs/index.php
You are successfully logged in. <?php echo $this->Html->link('logout',[ "controller" => "Authexs","action" => "logout" ]); ?>
Execute the above example by visiting the following URL.
http://localhost/cakephp4/auth
由于身份验证已完成,一旦您尝试访问上述网址,您将被重定向到如下所示的登录页面。
提供正确的凭据后,您将登录并重定向到如下所示的屏幕。
点击注销链接后,您将再次重定向到登录屏幕。
系统故障需要得到有效的处理,以保证系统的顺利运行。 CakePHP 带有默认的错误捕获,当发生错误时打印并记录错误。同样的错误处理程序用于捕获异常。
错误处理程序在 debug 为 true 时显示错误,并在 debug 为 false 时记录错误。 CakePHP 有许多异常类,内置的异常处理将捕获任何未捕获的异常并呈现有用的页面。
错误和异常可以在文件configapp.php中配置。错误处理接受一些选项,允许您为应用程序定制错误处理 -
选项 | 数据类型 | 描述 | |||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
错误级别 | int |
|
|||||||||||||||||||||
跟踪 | 布尔 | 在日志文件中包含错误的堆栈跟踪。每次错误后,堆栈跟踪将包含在日志中。这有助于查找发生错误的位置/时间。 | |||||||||||||||||||||
异常渲染器 | 字符串 | 负责渲染未捕获异常的类。如果您选择自定义类,则应将该类的文件放置在src/Error中。该类需要实现 render() 方法。 | |||||||||||||||||||||
日志 | 布尔 | 当 true 时,异常及其堆栈跟踪将被记录到 CakeLogLog。 | |||||||||||||||||||||
跳过日志 | 数组 | 不应记录的异常类名称数组。这对于删除 NotFoundExceptions 或其他常见但无趣的日志消息很有用。 | |||||||||||||||||||||
额外的致命错误内存 | int | 设置为在遇到致命错误时增加内存限制的兆字节数。这为完成日志记录或错误处理提供了喘息的空间。 |
Syntax | write( integer|string $level, mixed $message, string|array $context [] ) |
---|---|
Parameters |
The severity level of the message being written. The value must be an integer or string matching a known level. Message content to log. Additional data to be used for logging the message. The special scope key can be passed to be used for further filtering of the log engines to be used. If a string or a numerically index array is passed, it will be treated as the scope key. See Cake\Log\Log::config() for more information on logging scopes. |
Returns | boolean |
Description | Writes the given message and type to all of the configured log adapters. Configured adapters are passed both the $level and $message variables. $level is one of the following strings/values. |
The second is to use the log() shortcut function available on any using the LogTrait Calling log() will internally call Log::write() −
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages', ['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('logex',['controller'=>'Logexs','action'=>'index']); $builder->fallbacks(); });
Create a LogexsCakePHP 快速指南.php file at src/CakePHP 快速指南/LogexsCakePHP 快速指南.php. Copy the following code in the controller file.
src/CakePHP 快速指南/LogexsCakePHP 快速指南.php
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; use Cake\Log\Log; class LogexsCakePHP 快速指南 extends AppCakePHP 快速指南{ public function index(){ /*The first way to write to log file.*/ Log::write('debug',"Something didn't work."); /*The second way to write to log file.*/ $this->log("Something didn't work.",'debug'); } } ?>
Create a directory Logexs at src/Template and under that directory create a View file called index.php. Copy the following code in that file.
src/Template/Logexs/index.php
Something is written in log file. Check log file logs\debug.log
Execute the above example by visiting the following URL.
http://localhost/cakephp4/logex
Upon execution, you will receive the following output.
The logs will be added to log/debug.log file −
CakePHP provides various in built tags to handle HTML forms easily and securely. Like many other PHP frameworks, major elements of HTML are also generated using CakePHP. Following are the various functions used to generate HTML elements.
The following functions are used to generate select options −
Syntax | _selectCakePHP 快速指南( array $elementsarray(), array $parentsarray(), boolean $showParentsnull, array $attributesarray() ) |
---|---|
Parameters |
|
Returns | array |
Description | Returns an array of formatted OPTION/OPTGROUP elements |
The following functions are used to generate HTML select element.
Syntax | select( string $fieldCakePHP 快速指南, array $options array(), array $attributes array() ) |
---|---|
Parameters |
CakePHP 快速指南 attribute of the SELECT Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the SELECT element. |
Returns | Formatted SELECT element. |
Description | Returns a formatted SELECT element. |
The following functions are used to generate button on HTML page.
Syntax | Button(string $title, array $optionsarray() ) |
---|---|
Parameters |
|
Returns | HTML button tag. |
Description | Creates a tag. The type attribute defaults to type="submit". You can change it to a different value by using $options['type']. |
The following functions are used to generate checkbox on HTML page.
Syntax | Checkbox(string $fieldCakePHP 快速指南, array $optionsarray() ) |
---|---|
Parameters |
|
Returns | An HTML text input element. |
Description | Creates a checkbox input widget. |
以下函数用于在 HTML 页面上创建表单。
语法 | create(混合$modelnull,数组$optionsarray()) | ||||||||
---|---|---|---|---|---|---|---|---|---|
参数 |
|
||||||||
返回 | 格式化的开始 FORM 标签。 | ||||||||
描述 | 返回 HTML FORM 元素。 |
Syntax | file(string $fieldCakePHP 快速指南, array $optionsarray() ) |
---|---|
Parameters |
|
Returns | A generated file input. |
Description | Creates file input widget. |
。
语法 | 文件(字符串 $fieldCakePHP 快速指南, 数组 $optionsarray() ) | ||||||||
---|---|---|---|---|---|---|---|---|---|
参数 |
|
||||||||
返回 | 生成的文件输入。 | ||||||||
描述 | 创建文件输入小部件。
|
语法 |
|
||||||||
---|---|---|---|---|---|---|---|---|---|
参数 |
|
||||||||
返回 | 生成的隐藏输入
|
||||||||
描述 | 创建隐藏输入字段 |
语法 | 输入(字符串 $fieldCakePHP 快速指南 , 数组 $options array() ) |
---|---|
参数 |
|
返回 | 已完成的表单小部件 |
描述 | 生成一个包含标签和包装 div 的表单输入元素 |
语法 | Radio(字符串 $fieldCakePHP 快速指南 , 数组 $optionsarray() , 数组 $attributesarray() ) TD> |
---|---|
参数 |
|
返回 | 完成的无线电小部件集 |
描述 | 创建一组无线电小部件。默认情况下将创建图例和字段集。使用 $options 来控制它。 |
语法 | 提交(字符串 $caption null,数组 $options array() ) |
---|---|
参数 |
|
返回 | HTML 提交按钮 |
描述 | 创建一个提交按钮元素。此方法将生成 可用于使用 $options 提交和重置表单的元素。可以通过为 $caption 提供图像路径来创建图像提交。 |
Syntax | Textarea(string $fieldCakePHP 快速指南 , array $options array() ) |
---|---|
Parameters |
|
Returns | A generated HTML text input element |
Description | Creates a textarea widget |
Make changes in the config/routes.php file as shown in the following code.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('register',['controller'=>'Registrations','action'=>'index']); $builder->fallbacks(); });
Create a RegistrationsCakePHP 快速指南.php file at
src/CakePHP 快速指南/RegistrationsCakePHP 快速指南.php. Copy the following code in the controller file.
src/CakePHP 快速指南/RegistrationsCakePHP 快速指南.php
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; class RegistrationsCakePHP 快速指南 extends AppCakePHP 快速指南{ public function index(){ $country = array('India','United State of America','United Kingdom'); $this->set('country',$country); $gender = array('Male','Female'); $this->set('gender',$gender); } } ?>
Create a directory Registrations at src/Template and under that directory, create a View file called index.php. Copy the following code in that file.
src/Template/Registrations/index.php
<?php echo $this->Form->create(NULL,array('url'=>'/register')); echo '<label for="country">Country</label>'; echo $this->Form->select('country',$country); echo '<label for="gender">Gender</label>'; echo $this->Form->radio('gender ',$gender); echo '<label for="address">Address</label>'; echo $this->Form->textarea('address'); echo $this->Form->file('profilepic'); echo '<div>'.$this->Form->checkbox('terms'). '<label for="country">Terms ∓ CakePHP 快速指南s</label> </div>'; echo $this->Form->button('Submit'); echo $this->Form->end(); ?>
Execute the above example by visiting the following URL −
http://localhost/cakephp4/register
Upon execution, you will receive the following output.
Like many other frameworks, CakePHP also supports Internationalization. We need to follow these steps to go from single language to multiple language.
Create a separate locales directory resources\locales.
Create subdirectory for each language, under the directory src\Locale. The name of the subdirectory can be two letter ISO code of the language or full locale name like en_US, fr_FR etc.
Create separate default.po file under each language subdirectory. This file contains entry in the form of msgid and msgstr, as shown in the following program.
msgid "msg" msgstr "CakePHP Internationalization example."
Here, the msgid is the key which will be used in the View template file and msgstr is the value which stores the translation.
In the View template file, we can use the above msgid, as shown below which will be translated based on the set value of locale.
<?php echo __('msg'); ?>
The default locale can be set in the config/app.php file by the following line.
'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US')
To change the local at runtime, we can use the following lines.
use Cake\I18n\I18n; I18n::locale('de_DE');
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages', ['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('locale', ['controller'=>'Localizations','action'=>'index']); $builder->fallbacks(); });
Create a LocalizationsCakePHP 快速指南.php file at src/CakePHP 快速指南/LocalizationsCakePHP 快速指南.php. Copy the following code in the controller file.
src/CakePHP 快速指南/LocalizationsCakePHP 快速指南.php
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; use Cake\I18n\I18n; class LocalizationsCakePHP 快速指南 extends AppCakePHP 快速指南 { public function index() { if($this->request->is('post')) { $locale = $this->request->getData('locale'); I18n::setLocale($locale); } } } ?>
Create a locales directory at resources\locales. Create 3 directories called en_US, fr_FR, de_DE under the locales directory. Create a file under each directory called default.po. Copy the following code in the respective file.
resources/locales/en_US/default.po
msgid "msg" msgstr "CakePHP Internationalization example."
resources/locales/fr_FR/default.po
msgid "msg" msgstr "Exemple CakePHP internationalisation."
resources/locales/de_DE/default.po
msgid "msg" msgstr "CakePHP Internationalisierung Beispiel."
Create a directory Localizations at src/Template and under that directory, create a View file called index.php. Copy the following code in that file.
src/Template/Localizations/index.php
Form->create(NULL,array('url'=>'/locale')); echo $this->Form->radio("locale", [ ['value'=>'en_US','text'=>'CakePHP 快速指南'], ['value'=>'de_DE','text'=>'German'], ['value'=>'fr_FR','text'=>'French'], ] ); echo $this->Form->button('Change Language'); echo $this->Form->end(); ?> <?php echo __('msg'); ?>
Execute the above example by visiting the following URL. http://localhost/cakephp4/locale
Upon execution, you will receive the following output.
CakePHP provides Email class to manage email related functionalities. To use email functionality in any controller, we first need to load the Email class by writing the following line.
use Cake\Mailer\Email;
The Email class provides various useful methods which are described below.
Syntax | From(string|array|null $email null, string|null $name null ) |
---|---|
Parameters |
|
Returns | array|$this |
Description | It specifies from which email address; the email will be sent |
Syntax | To(string|array|null $emailnull, string|null $namenull) |
---|---|
Parameters |
|
Returns | array|$this |
Description | It specifies to whom the email will be sent |
Syntax | Send(string|array|null $contentnull) |
---|---|
Parameters |
|
Returns | array |
Description | Send an email using the specified content, template and layout |
Syntax | Subject(string|null $subjectnull) |
---|---|
Parameters |
|
Returns | array|$this |
Description | Get/Set Subject |
Syntax | Attachments(string|array|null $attachmentsnull) |
---|---|
Parameters |
|
Returns | array|$this |
Description | Add attachments to the email message |
Syntax | Bcc(string|array|null $emailnull, string|null $namenull) |
---|---|
Parameters |
|
Returns | array|$this |
Description | Bcc |
Syntax | cc( string|array|null $emailnull , string|null $namenull ) |
---|---|
Parameters |
|
Returns | array|$this |
Description | Cc |
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('/email',['controller'=>'Emails','action'=>'index']); $builder->fallbacks(); });
Create an EmailsCakePHP 快速指南.php file at src/CakePHP 快速指南/EmailsCakePHP 快速指南.php. Copy the following code in the controller file.
src/CakePHP 快速指南/EmailsCakePHP 快速指南.php
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; use Cake\Mailer\Email; class EmailsCakePHP 快速指南 extends AppCakePHP 快速指南{ public function index(){ $email = new Email('default'); $email->to('abc@gmail.com') ->subject('About') ->send('My message'); } } ?>
Create a directory Emails at src/Template and under that directory, create a View file called index.php. Copy the following code in that file.
src/Template/Emails/index.php
Email Sent.
Before we send any email, we need to configure it. In the below screenshot, you can see that there are two transports, default and Gmail. We have used Gmail transport.
You need to replace the “GMAIL USERNAME” with your Gmail username and “APP PASSWORD” with your applications password. You need to turn on 2-step verification in Gmail and create a new APP password to send email.
config/app.php
Execute the above example by visiting the following URL − http://localhost/cakephp/email
Upon execution, you will receive the following output.
Session allows us to manage unique users across requests, and stores data for specific users. Session data can be accessible anywhere, anyplace, where you have access to request object, i.e., sessions are accessible from controllers, views, helpers, cells, and components.
Session object can be created by executing the following code.
$session = $this->request->session();
To write something in session, we can use the write() session method.
Session::write($key, $value)
The above method will take two arguments, the value and the key under, which the value will be stored.
$session->write('name', 'CakePHP 快速指南 Gandhi');
To retrieve stored data from session, we can use the read() session method.
Session::read($key)
The above function will take only one argument, that is the key of the value, which was used at the time of writing session data. Once the correct key was provided, then the function will return its value.
$session->read('name');
When you want to check whether, particular data exists in the session or not, then you can use the check() session method.
Session::check($key)
The above function will take only key as the argument.
if ($session->check('name')) { // name exists and is not null. }
To delete data from session, we can use the delete() session method to delete the data.
Session::delete($key)
The above function will take only key of the value to be deleted from session.
$session->delete('name');
When you want to read and then delete data from session then, we can use the consume() session method.
static Session::consume($key)
The above function will take only key as argument.
$session->consume('name');
We need to destroy a user session, when the user logs out from the site and to destroy the session the destroy() method is used.
Session::destroy()
$session->destroy();
Destroying session will remove all session data from server, but will not remove session cookie.
In a situation, where you want to renew user session then, we can use the renew() session method.
Session::renew()
$session->renew();
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('/session-object',['controller'=>'Sessions','action'=>'index']); $builder->connect('/session-read',['controller'=>'Sessions','action'=>'retrieve_session_data']); $builder->connect('/session-write',['controller'=>'Sessions','action'=> 'write_session_data']); $builder->connect('/session-check',['controller'=>'Sessions','action'=>'check_session_data']); $builder->connect('/session-delete',['controller'=>'Sessions','action'=>'delete_session_data']); $builder->connect('/session-destroy',['controller'=>'Sessions','action'=>'destroy_session_data']); $builder->fallbacks(); });
Create a SessionsCakePHP 快速指南.php file at src/CakePHP 快速指南/SessionsCakePHP 快速指南.php. Copy the following code in the controller file
src/CakePHP 快速指南/SessionsCakePHP 快速指南.php
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; class SessionsCakePHP 快速指南 extends AppCakePHP 快速指南 { public function retrieveSessionData() { //create session object $session = $this->request->getSession(); //read data from session $name = $session->read('name'); $this->set('name',$name); } public function writeSessionData(){ //create session object $session = $this->request->getSession(); //write data in session $session->write('name','CakePHP 快速指南 Gandhi'); } public function checkSessionData(){ //create session object $session = $this->request->getSession(); //check session data $name = $session->check('name'); $address = $session->check('address'); $this->set('name',$name); $this->set('address',$address); } public function deleteSessionData(){ //create session object $session = $this->request->getSession(); //delete session data $session->delete('name'); } public function destroySessionData(){ //create session object $session = $this->request->getSession(); //destroy session $session->destroy(); } } ?>
Create a directory Sessions at src/Template and under that directory create a View file called write_session_data.php. Copy the following code in that file.
src/Template/Sessions/write_session_data.php
The data has been written in session.
Create another View file called retrieve_session_data.php under the same Sessions directory and copy the following code in that file.
src/Template/Sessions/retrieve_session_data.php
Here is the data from session. CakePHP 快速指南: =$name;?>
Create another View file called check_session_data.ctp under the same Sessions directory and copy the following code in that file.
src/Template/Sessions/check_session_data.ctp
<?php if($name): ?> name exists in the session. <?php else: ?> name doesn't exist in the database <?php endif;?> <?php if($address): ?> address exists in the session. <?php else: ?> address doesn't exist in the database <?php endif;?>
Create another View file called delete_session_data.ctp, under the same Sessions directory and copy the following code in that file.
src/Template/Sessions/delete_session_data.ctp
Data deleted from session.
Create another View file called destroy_session_data.ctp, under the same Sessions directory and copy the following code in that file.
src/Template/Sessions/destroy_session_data.ctp
Session CakePHP 快速指南.
Execute the above example by visiting the following URL. This URL will help you write data in session.
http://localhost/cakephp4/session-write
Visit the following URL to read session data − http://localhost/cakephp4/session-read
Visit the following URL to check session data − http://localhost/cakephp4/session-check
Visit the following URL to delete session data − http://localhost/cakephp4/session-delete Visit the
Visit the following URL to destroy session data − http://localhost/cakephp4/session-destroy
Handling CakePHP 快速指南 with CakePHP is easy and secure. There is a CakePHP 快速指南Component class which is used for managing CakePHP 快速指南. The class provides several methods for working with CakePHP 快速指南s.
To work with cookies, add this 2 classes to your controller −
use Cake\Http\CakePHP 快速指南\CakePHP 快速指南; use Cake\Http\CakePHP 快速指南\CakePHP 快速指南Collection;
The cookie object has to be created first to register a cookie.
$cookie = new CakePHP 快速指南(name,value,expiration time,path,domain);
The name and value are mandatory and others are optional param.
Following is the syntax to write a cookie.
$cookie = new CakePHP 快速指南(name,value,expiration time,path,domain);
The cookie created has to be added to cookieCollection as shown below −
$cookie = new CakePHP 快速指南('name','XYZ'); $cookies = new CakePHP 快速指南Collection([$cookie]);
If the cookie collection object is already created, the rest of the cookies can be added as shown below −
$cookies = $cookies->add($cookie);
To read cookie make use of get() method from cookiecollection.
The syntax for read cookie is as follows −
Cake\Http\CakePHP 快速指南\CakePHP 快速指南Collection::get($name)
This will return you cookiecollection Interface, to get the value of the cookie, you will have to call the method getValue().
Cake\Http\CakePHP 快速指南\CakePHP 快速指南Collection Interface::getValue()
The has() method from cookieCollection will tell you, if the cookie is present or not.
Cake\Http\CakePHP 快速指南\CakePHP 快速指南Collection::has($name)
echo $isPresent = $this->cookies->has('name');
The remove() method is used to delete cookie. Following is the syntax of the remove() method.
Cake\Http\CakePHP 快速指南\CakePHP 快速指南Collection::remove($name)
The remove() method will take one argument, the name of cookie variable ($name) to delete.
$test = $this->cookies->remove('name');
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('cookie/testcookies',['controller'=>'CakePHP 快速指南s','action'=>'testCakePHP 快速指南s']); $builder->fallbacks(); });
Create a CakePHP 快速指南sCakePHP 快速指南.php file at src/CakePHP 快速指南/CakePHP 快速指南sCakePHP 快速指南.php. Copy the following code in the controller file.
src/CakePHP 快速指南/CakePHP 快速指南s/CakePHP 快速指南sCakePHP 快速指南.php
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; use Cake\Http\CakePHP 快速指南\CakePHP 快速指南; use Cake\Http\CakePHP 快速指南\CakePHP 快速指南Collection; class CakePHP 快速指南sCakePHP 快速指南 extends AppCakePHP 快速指南{ public $cookies; public function testCakePHP 快速指南s() { $cookie = new CakePHP 快速指南('name','XYZ'); $this->cookies = new CakePHP 快速指南Collection([$cookie]); $cookie_val = $this->cookies->get('name'); $this->set('cookie_val',$cookie_val->getValue()); $isPresent = $this->cookies->has('name'); $this->set('isPresent',$isPresent); $this->set('count', $this->cookies->count()); $test = $this->cookies->remove('name'); $this->set('count_afterdelete', $test->count()); } } ?>
Create a directory CakePHP 快速指南s at src/Template and under that directory create a View file called test_cookies.php. Copy the following code in that file.
src/Template/CakePHP 快速指南/test_cookies.php
The value of the cookie is: <?php echo $cookie_val; ?> <br> <?php if($isPresent): ?> The cookie is present. <?php else: ?> The cookie isn't present. <?php endif; ?> <br> <?php echo "The count of cookie before delete is :" .$count; ?> <br> <?php echo "The count of cookie after delete is :" .$count_afterdelete; ?>
Execute the above example by visiting the following URL − http://localhost/cakephp4/cookie/testcookies
Security is another important feature while building web applications. It assures the users of the website that, their data is secured. CakePHP provides some tools to secure your application.
Security library in CakePHP provides methods, by which we can encrypt and decrypt data. Following are the two methods, which are used for the same purpose.
static Cake\Utility\Security::encrypt($text, $key, $hmacSalt = null) static Cake\Utility\Security::decrypt($cipher, $key, $hmacSalt = null)
The encrypt method will take text and key as the argument to encrypt data and the return value will be the encrypted value with HMAC checksum.
To hash a data, hash() method is used. Following is the syntax of the hash() method.
static Cake\Utility\Security::hash($string, $type = NULL, $salt = false)
CSRF stands for Cross Site Request Forgery. By enabling the CSRF Component, you get protection against attacks. CSRF is a common vulnerability in web applications.
It allows an attacker to capture and replay a previous request, and sometimes submit data requests using image tags or resources on other domains. The CSRF can be enabled by simply adding the CsrfComponent to your components array as shown below −
public function initialize(): void { parent::initialize(); $this->loadComponent('Csrf'); }
The CsrfComponent integrates seamlessly with FormHelper. Each time you create a form with FormHelper, it will insert a hidden field containing the CSRF token.
While this is not recommended, you may want to disable the CsrfComponent on certain requests. You can do so by using the controller’s event dispatcher, during the beforeFilter() method.
public function beforeFilter(Event $event) { $this->eventManager()->off($this->Csrf); }
Security Component applies tighter security to your application. It provides methods for various tasks like −
Restricting which HTTP methods your application accepts − You should always verify the HTTP method, being used before executing side-effects. You should check the HTTP method or use Cake\Network\Request::allowMethod() to ensure the correct HTTP method is used.
Form tampering protection − By default, the SecurityComponent prevents users from tampering with forms in specific ways. The SecurityComponent will prevent the following things −
Unknown fields cannot be added to the form.
Fields cannot be removed from the form.
Values in hidden inputs cannot be modified.
Requiring that SSL be used − All actions to require a SSL- secured
Limiting cross controller communication − We can restrict which controller can send request to this controller. We can also restrict which actions can send request to this controller’s action.
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages', ['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('login',['controller'=>'Logins','action'=>'index']); $builder->fallbacks(); });
Create a LoginsCakePHP 快速指南.php file at src/CakePHP 快速指南/LoginsCakePHP 快速指南.php. Copy the following code in the controller file.
src/CakePHP 快速指南/LoginsCakePHP 快速指南.php
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; class LoginsCakePHP 快速指南 extends AppCakePHP 快速指南 { public function initialize() : void { parent::initialize(); $this->loadComponent('Security'); } public function index(){ } } ?>
Create a directory Logins at src/Template and under that directory create a View file called index.php. Copy the following code in that file.
src/Template/Logins/index.php
<?php echo $this->Form->create(NULL,array('url'=>'/login')); echo $this->Form->control('username'); echo $this->Form->control('password'); echo $this->Form->button('Submit'); echo $this->Form->end(); ?>
Execute the above example by visiting the following URL − http://localhost/cakephp4/login
Upon execution, you will receive the following output.
Often while making websites, we need to validate certain things before processing data further. CakePHP provides validation package, to build validators that can validate data with ease.
CakePHP provides various validation methods in the Validation Class. Some of the most popular of them are listed below.
Syntax | Add(string $field, array|string $name, array|Cake\Validation\ValidationRule $rule [] ) |
---|---|
Parameters |
|
Returns | $this |
Description | Adds a new rule to a field's rule set. If second argument is an array, then rules list for the field will be replaced with second argument and third argument will be ignored. |
Syntax | allowEmpty(string $field, boolean|string|callable $whentrue, string|null $messagenull) |
---|---|
Parameters |
|
Returns | $this |
Description | Allows a field to be empty. |
Syntax | alphanumeric (string $field, string|null $messagenull, string|callable|null $whennull) |
Parameters |
|
Returns | $this |
Description | Add an alphanumeric rule to a field. |
Syntax | creditCard(string $field , string $type'all', string|null $messagenull, string|callable|null $whennull) |
---|---|
Parameters |
|
Returns | $this |
Description | Add a credit card rule to a field. |
Syntax | Email(string $field , boolean $checkMXfalse, string|null $messagenull, string|callable|null, $whennull) |
---|---|
Parameters |
|
Returns | $this |
Description | Add an email validation rule to a field. |
Syntax | maxLength(string $field, integer $max, string|null $messagenull, string|callable|null $whennull) |
---|---|
Parameters |
|
Returns | $this |
Description | Add a string length validation rule to a field. |
Syntax | minLength(string $field, integer $min, string|null $messagenull, string|callable|null $whennull) |
---|---|
Parameters |
|
Returns | $this |
Description | Add a string length validation rule to a field. |
Syntax | notBlank(string $field, string|null $messagenull, string|callable|null $whennull) |
---|---|
Parameters |
|
Returns | $this |
Description | Add a notBlank rule to a field. |
Validator can be created by adding the following two lines in the controller.
use Cake\Validation\Validator; $validator = new Validator();
Once, we have created validator, we can use the validator object to validate data. The following code explains, how we can validate data for login webpage.
$validator->notEmpty('username', 'We need username.')->add( 'username', 'validFormat', ['rule' => 'email','message' => 'E-mail must be valid']); $validator->notEmpty('password', 'We need password.'); $errors = $validator->errors($this->request->data());
Using the $validator object, we have first called the notEmpty() method, which will ensure that the username must not be empty. After that, we have chained the add() method to add one more validation for proper email format.
After that we have added validation for password field with notEmpty() method, which will confirm that password field must not be empty.
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('validation',['controller'=>'Valids','action'=>'index']); $builder->fallbacks(); });
Create a ValidsCakePHP 快速指南.php file at src/CakePHP 快速指南/ValidsCakePHP 快速指南.php. Copy the following code in the controller file.
src/CakePHP 快速指南/ValidsCakePHP 快速指南.php
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; use Cake\Validation\Validator; class ValidsCakePHP 快速指南 extends AppCakePHP 快速指南{ public function index(){ $validator = new Validator(); $validator->notEmpty('username', 'We need username.')->add( 'username', 'validFormat', ['rule' => 'email','message' => 'E-mail must be valid']); $validator->notEmpty('password', 'We need password.'); $errors = $validator->errors($this->request->getData()); $this->set('errors',$errors); } } ?>
Create a directory Valids at src/Template and under that directory create a View file called index.php. Copy the following code in that file.
src/Template/Valids/index.php
<?php if($errors) { foreach($errors as $error) foreach($error as $msg) echo '<font color="red">'.$msg.'<br>'; } else { echo "No errors."; } echo $this->Form->create(NULL,array('url'=>'/validation')); echo $this->Form->control('username'); echo $this->Form->control('password'); echo $this->Form->button('Submit'); echo $this->Form->end(); ?>
Execute the above example by visiting the following URL −
http://localhost/cakephp4/validation
Click on the submit button without entering anything. You will receive the following output.
The http client can be used to make requests like GET, POST, PUT etc.
To work with http client, add the following −
use Cake\Http\Client;
Let us work on example to understand working of HTTP client.
To get the data from give http url, you can do as follows −
$response = $http->get('https://jsonplaceholder.typicode.com/users');
In case, you need to pass some query params, they can be passed as follows −
$response = $http->get('https://jsonplaceholder.typicode.com/users', ["id", 1]);
To get the response, you can do as follows −
For normal text data −
$response->getBody();
For Json −
$response->getJson();
For Xml −
$response->getXml()
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('getData',['controller'=>'Requests','action'=>'index']); $builder->fallbacks(); });
Create a RequestsCakePHP 快速指南.php file at src/CakePHP 快速指南/RequestsCakePHP 快速指南.php. Copy the following code in the controller file.
src/CakePHP 快速指南/RequestsCakePHP 快速指南.php
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; use Cake\Http\Client; class RequestsCakePHP 快速指南 extends AppCakePHP 快速指南{ public function index(){ $http = new Client(); $response = $http->get('https://jsonplaceholder.typicode.com/users'); $stream = $response->getJson(); $this->set('response',$stream); } } ?>
Create a directory Requests at src/Template and under that directory create a View file called index.php. Copy the following code in that file.
src/Template/Requests/index.php
<h3>All Users from url : https://jsonplaceholder.typicode.com/users</h3> <?php if($response) { foreach($response as $res => $val) { echo '<font color="gray">CakePHP 快速指南: '.$val["name"].' Email -'.$val["email"].'</font><br>'; } } ?>
Execute the above example by visiting the following URL −
http://localhost/cakephp4/getData
Click on the submit button without entering anything. You will receive the following output.
To work with post, you need to call $http client as follows −
$response = $http->post('yoururl', data);
Let us see one example on the same.
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('postData',['controller'=>'Requests','action'=>'index']); $builder->fallbacks(); });
Create a RequestsCakePHP 快速指南.php file at src/CakePHP 快速指南/RequestsCakePHP 快速指南.php. Copy the following code in the controller file. Ignore if already created.
src/CakePHP 快速指南/RequestsCakePHP 快速指南.php
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; use Cake\Http\Client; class RequestsCakePHP 快速指南 extends AppCakePHP 快速指南{ public function index(){ $http = new Client(); $response = $http->post('https://postman-echo.com/post', [ 'name'=> 'ABC', 'email' => 'xyz@gmail.com' ]); } } ?>
Create a directory Requests at src/Template and under that directory create a View file called index.php. Copy the following code in that file.
src/Template/Requests/index.php
<h3>Testing Post Method</h3>
Execute the above example by visiting the following URL −
http://localhost/cakephp4/postData
Given below is the output of the code −
Similarly, you can try for PUT method.
$http = new Client(); $response = $http->put('https://postman-echo.com/post', [ 'name'=> 'ABC', 'email' => 'xyz@gmail.com' ]);
If we want to show a set of data that is huge, we can use pagination and this feature is available with cake php 4 which is very easy to use.
We have a table titled “articles” with following data −
Let us use pagination to display the data in the form of pages, instead of showing them all together.
Make Changes in the config/routes.php file as shown in the following program.
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('posts',['controller'=>'Posts','action'=>'index']); $builder->fallbacks(); });
Create a PostsCakePHP 快速指南.php file at src/CakePHP 快速指南/PostsCakePHP 快速指南.php. Copy the following code in the controller file. Ignore, if already created.
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; class PostsCakePHP 快速指南 extends AppCakePHP 快速指南 { public function index(){ $this->loadModel('articles'); $articles = $this->articles->find('all')->order(['articles.id ASC']); $this->set('articles', $this->paginate($articles, ['limit'=> '3'])); } } ?>
The data from articles table is fetched using −
$this->loadModel('articles'); $articles = $this->articles->find('all')->order(['articles.id ASC']);
To apply pagination and we would show the data with 3 per records and the same is done as follows −
$this->set('articles', $this->paginate($articles, ['limit'=> '3']));
This is enough to activate pagination on the articles tables.
Create a directory Posts at src/Template and under that directory create a Viewfile called index.php. Copy the following code in that file.
<div> <?php foreach ($articles as $key=>$article) {?> <a href="#"> <div> <p>= $article->title ?> </p> <p>= $article->details ?></p> </div> </a> <br> <?php } ?> <ul class="pagination"> = $this->Paginator->prev(" = $this->Paginator->numbers() ?> = $this->Paginator->next(">>") ?> </ul> </div>
The pagination for the list of pages is done as follows −
Execute the above example by visiting the following URL −
http://localhost/cakephp4/posts
When you run the code, you will see the following output −
Click on the numbers below, to switch to next page, or use the next or previous button.
For example
You will see that page=2 is appended to the page url in the browser.
To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.
To work with date and time, include the class in your controller
use Cake\I18n\FrozenTime;
Let us work, on an example and display date and time, using FrozenTime class.
Make Changes in the config/routes.php file as shown in the following program.
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('datetime',['controller'=>'Dates','action'=>'index']); $builder->fallbacks(); });
Create a DatesCakePHP 快速指南.php file at src/CakePHP 快速指南/DatesCakePHP 快速指南.php. Copy the following code in the controller file. Ignore if already created.
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; use Cake\I18n\FrozenTime; class DatesCakePHP 快速指南 extends AppCakePHP 快速指南{ public function index(){ $time = FrozenTime::now(); $now = FrozenTime::parse('now'); $_now = $now->i18nFormat('yyyy-MM-dd HH:mm:ss'); $this->set('timenow', $_now); $now = FrozenTime::parse('now'); $nice = $now->nice(); $this->set('nicetime', $nice); $hebrewdate = $now->i18nFormat(\IntlDateFormatter::FULL, null, 'en-IR@calendar=hebrew'); $this->set("hebrewdate",$hebrewdate); $japanesedate = $now->i18nFormat(\IntlDateFormatter::FULL, null, 'en-IR@calendar=japanese'); $this->set("japanesedate",$japanesedate); $time = FrozenTime::now(); $this->set("current_year",$time->year); $this->set("current_month",$time->month); $this->set("current_day",$time->day); } } ?>
Create a directory Dates at src/Template and under that directory create a View file called index.php. Copy the following code in that file.
<?php echo "The Current date and time is = ".$timenow; echo "<br/>"; echo "Using nice format available = ".$nicetime; echo "<br>"; echo "Date and Time as per Hebrew Calender =" .$hebrewdate; echo "<br>"; echo "Date and Time as per Japanese Calender =" .$japanesedate; echo "<br>"; echo "Current Year = ".$current_year; echo "<br>"; echo "Current Month = ".$current_month; echo "<br>"; echo "Current Day = ".$current_day; ?>
Execute the above example by visiting the following URL −
http://localhost/cakephp4/datetime
When you run the code, you will see the following output −
To work on file upload we are going to use the form helper. Here, is an example for file upload.
Make Changes in the config/routes.php file, as shown in the following program.
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('fileupload',['controller'=>'Files','action'=>'index']); $builder->fallbacks(); });
Create a FilesCakePHP 快速指南.php file at src/CakePHP 快速指南/FilesCakePHP 快速指南.php. Copy the following code in the controller file. Ignore, if already created.
Create uploads/ directory in src/. The files uploaded will be saved in uploads/ folder.
<?php namespace App\CakePHP 快速指南; use App\CakePHP 快速指南\AppCakePHP 快速指南; use Cake\View\Helper\FormHelper; class FilesCakePHP 快速指南 extends AppCakePHP 快速指南 { public function index(){ if ($this->request->is('post')) { $fileobject = $this->request->getData('submittedfile'); $uploadPath = '../uploads/'; $destination = $uploadPath.$fileobject->getClientFilename(); // Existing files with the same name will be replaced. $fileobject->moveTo($destination); } } } ?>
Create a directory Files at src/Template and under that directory create a View file called index.php. Copy the following code in that file.
<?php echo $this->Form->create(NULL, ['type' => 'file']); echo $this->l;Form->file('submittedfile'); echo $this->Form->button('Submit'); echo $this->Form->end(); $uploadPath ='../uploads/'; $files = scandir($uploadPath, 0); echo "Files uploaded in uploads/ are:<br>"; for($i = 2; $i "; ?>
The files saved in uploads/ folder is listed for the user. Execute the above example by visiting the following URL −
http://localhost/cakephp4/fileupload −
When you execute the above code, you should see the following output −
以上是CakePHP 快速指南的详细内容。更多信息请关注PHP中文网其他相关文章!