> 백엔드 개발 > PHP 튜토리얼 > CakePHP 빠른 가이드

CakePHP 빠른 가이드

WBOY
풀어 주다: 2024-09-10 17:27:17
원래의
1287명이 탐색했습니다.

CakePHP - 개요

CakePHP는 오픈 소스 MVC 프레임워크입니다. 이를 통해 애플리케이션 개발, 배포 및 유지 관리가 훨씬 쉬워집니다. CakePHP에는 가장 일반적인 작업의 과부하를 줄이기 위한 다양한 라이브러리가 있습니다.

CakePHP의 장점

CakePHP를 사용하면 다음과 같은 장점이 있습니다. −

  • 오픈소스

  • MVC 프레임워크

  • 템플릿 엔진

  • 캐싱 작업

  • 검색 엔진 친화적인 URL

  • 간편한 CRUD(생성, 읽기, 업데이트, 삭제) 데이터베이스 상호 작용.

  • 도서관 및 도우미

  • 내장된 유효성 검사

  • 현지화

  • 이메일, 쿠키, 보안, 세션 및 요청 처리 구성요소

  • AJAX, JavaScript, HTML 양식 등을 위한 보기 도우미

CakePHP 요청 주기

다음 그림은 CakePHP의 요청 수명 주기 작동 방식을 설명합니다.

CakePHP Works

일반적인 CakePHP 요청 주기는 사용자가 애플리케이션에서 페이지나 리소스를 요청하는 것으로 시작됩니다. 높은 수준에서 각 요청은 다음 단계를 거칩니다. −

  • 웹 서버 재작성 규칙은 요청을 webroot / index.php로 보냅니다.

  • 애플리케이션의 오토로더와 부트스트랩 파일이 실행됩니다.

  • 구성된 모든 디스패치 필터는 요청을 처리하고 선택적으로 응답을 생성할 수 있습니다.

  • 디스패처는 라우팅 규칙에 따라 적절한 컨트롤러와 작업을 선택합니다.

  • 컨트롤러의 작업이 호출되고 컨트롤러는 필요한 모델 및 구성 요소와 상호 작용합니다.

  • 컨트롤러는 응답 생성을 View에 위임하여 모델 데이터의 결과를 생성합니다.

  • 뷰는 HelpersCell을 사용하여 응답 본문과 헤더를 생성합니다.

  • 응답이 클라이언트에게 다시 전송됩니다.

CakePHP - 설치

이 장에서는 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 사용자의 경우 PHP 설치를 위해 www.tutorialspoint.com/php7/php7_installation_linux.htm에서 제공되는 Tutorials Point 웹사이트를 참조하세요.

컴포저 설치

https://getcomposer.org/download/에서 Composer로 이동하여 컴퓨터의 운영 체제(OS)에 따라 다운로드를 클릭하고 시스템에 Composer를 설치하세요. Windows 사용자를 위한 PATH 변수에 위치를 추가하면 어떤 디렉터리에서든 작곡가를 사용할 수 있습니다.

Composer 설치가 완료되면 이제 CakePHP 설치를 시작하겠습니다.

CakePHP 설치

Windows 사용자의 경우 wamp가 있는 폴더로 이동하여 www/ 폴더에 cakephp4/.

폴더를 만듭니다.

Linux 사용자의 경우 var/www/html/ 폴더를 만든 다음 cakephp4/ 폴더를 만듭니다.

  • cakephp4/는 CakePHP를 설치할 폴더입니다.

작곡기를 사용하여 다음 명령을 실행하세요. −

composer create-project --prefer-dist cakephp/app:4.0.3 cakephp4
로그인 후 복사

명령이 실행될 때 표시되는 내용입니다. −

Command Executes

설치가 완료되면 localhost를 사용하여 브라우저에서 프로젝트를 엽니다.

동일한 경로는 http://localhost/cakephp입니다.

Cakephp Page

CakePHP - 폴더 구조

여기에서는 CakePHP의 폴더 구조와 명명 규칙에 대해 알아봅니다. 먼저 폴더 구조를 이해해 보겠습니다.

폴더 구조

다음 스크린샷을 살펴보세요. CakePHP의 폴더 구조를 보여줍니다.

Structure of CakePHP

다음 표는 CakePHP의 각 폴더의 역할을 설명합니다 −

Sr.No 폴더 이름 및 설명
1

bin 폴더에는 Cake 콘솔 실행 파일이 들어 있습니다.

2

구성

config 폴더에는 CakePHP가 사용하는 (몇 가지) 구성 파일이 들어 있습니다. 데이터베이스 연결 세부 정보, 부트스트래핑, 핵심 구성 파일 등이 여기에 저장되어야 합니다.

3

로그

logs 폴더에는 일반적으로 로그 구성에 따라 로그 파일이 포함됩니다.

4

플러그인

플러그인 폴더는 애플리케이션에서 사용하는 플러그인이 저장되는 곳입니다.

5

자원

해당 로케일 폴더의 국제화용 파일이 여기에 저장됩니다. 예: 로케일/en_US.

6

src

src 폴더에서 마법을 부리실 수 있습니다. 애플리케이션 파일이 배치되는 곳이며 대부분의 애플리케이션 개발을 수행하게 됩니다. src 내부의 폴더를 조금 더 자세히 살펴보겠습니다.

  • 콘솔 - 애플리케이션에 대한 콘솔 명령과 콘솔 작업이 포함되어 있습니다.

  • 컨트롤러 - 애플리케이션의 컨트롤러와 해당 구성 요소가 포함되어 있습니다.

  • 모델 - 애플리케이션의 테이블, 엔터티 및 동작을 포함합니다.

  • 보기 프리젠테이션 클래스는 셀, 헬퍼 및 템플릿 파일에 배치됩니다.

7

템플릿

템플릿 프리젠테이션 파일은 요소, 오류 페이지, 레이아웃 및 보기 템플릿 파일에 저장됩니다.

8

테스트

tests 폴더에는 애플리케이션의 테스트 사례를 저장합니다.

9

tmp

tmp 폴더는 CakePHP가 임시 데이터를 저장하는 곳입니다. 저장되는 실제 데이터는 CakePHP 구성 방법에 따라 다르지만 이 폴더는 일반적으로 모델 설명 및 때로는 세션 정보를 저장하는 데 사용됩니다.

10

판매자

vendor 폴더에는 CakePHP 및 기타 애플리케이션 종속 항목이 설치됩니다. 이 폴더의 파일을 편집하지 않겠다고 개인적으로 약속하십시오. 코어를 수정하신 경우 도움을 드릴 수 없습니다.

11

웹루트

webroot 디렉토리는 애플리케이션의 공개 문서 루트입니다. 여기에는 공개적으로 접근할 수 있는 모든 파일이 포함되어 있습니다.

Naming Convention

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.

CakePHP 빠른 가이드 Convention

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.

File and Class CakePHP 빠른 가이드 Convention

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.

Database Conventions

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.

Model Conventions

For model, the classes are named as per database table, the names are plural, PascalCased and suffixed with Table.

For example, StudentDetailsTable, StudentMarksTable

View Conventions

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.

CakePHP - Project Configuration

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 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 −

Example

$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.

General Configuration

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 −

  • (bool) false - Doesn’t do anything (default).

  • (bool) true - Appends the timestamp, when debug is true.

  • (string) ‘force’ - Always appends the timestamp.

Databases Configuration

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.

Config/app_local.php

*/
   '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.

config/app.php

'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.

log
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

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 Configuration

Email can be configured in file config/app.php. It is not required to define email configuration in config/app.php. Email can be used without it. Just use the respective methods to set all configurations separately or load an array of configs. Configuration for Email defaults is created using config() and configTransport().

Email Configuration Transport

By defining transports separately from delivery profiles, you can easily re-use transport configuration across multiple profiles. You can specify multiple configurations for production, development and testing. Each transport needs a 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),
   ],
],
로그인 후 복사

Email Delivery Profiles

Delivery profiles allow you to predefine various properties about email messages from your application, and give the settings a name. This saves duplication across your application and makes maintenance and development easier. Each profile accepts a number of keys.

Following is an example of Email delivery profiles.

'Email' => [
   'default' => [
   
      'transport' => 'default',
      'from' => 'you@localhost',
   ],
],
로그인 후 복사

CakePHP - Routing

In this chapter, we are going to learn the following topics related to routing −

  • Introduction to Routing
  • Connecting Routes
  • Passing CakePHP 빠른 가이드 to Routes
  • Generating urls
  • CakePHP 빠른 가이드 urls

Introduction 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 −

  • static method
  • scoped route builder

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.

Connecting Routes

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']
);
로그인 후 복사

Example

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/

Output

The above URL will yield the following output.

Above URL

Passed CakePHP 빠른 가이드

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.

As arguments to the action method

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.

As numericallyindexed array

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.

Using routing array

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.

Example

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

Output

Upon execution, the above URL will produce the following output.

Passed Argument

Generating URLs

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.

Example

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

Output

The above URL will produce the following output −

Generating URL

CakePHP 빠른 가이드 Routing

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.

Example

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

Output for URL 1

Execute URL

URL 2 − http://localhost/cakephp4/redirect

Output for URL 2

You will be redirected to https://tutorialspoint.com

CakePHP - CakePHP 빠른 가이드s

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 빠른 가이드.

AppCakePHP 빠른 가이드

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.

CakePHP 빠른 가이드 Actions

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.

Example

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.

CakePHP 빠른 가이드ing

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.

Example

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

Output

Upon execution, you will receive the following output.

CakePHP 빠른 가이드

Now, visit the following URL: http://localhost/cakephp4/redirect-controller2

The above URL will give you the following output.

CakePHP 빠른 가이드

Loading Models

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.

Example

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');
로그인 후 복사

CakePHP - Views

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.

View Templates

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 CakePHP 빠른 가이드

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.

Example

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

Output

The above URL will produce the following output.

CakePHP 빠른 가이드

CakePHP - Extending Views

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.

Example

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('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.

src/CakePHP 빠른 가이드/ExtendsCakePHP 빠른 가이드.php

<?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.

src/Template/Extends/header.php

<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.

src/Template/Extends/index.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

Output

Upon execution, you will receive the following output.

Common Header

CakePHP - View Elements

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.

Example

Create an element file at src/Template/element directory called helloworld.php. Copy the following code in that file.

src/Template/element/helloworld.php

<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.

src/Template/Elems/index.php

Element Example: <?php echo $this->element('helloworld'); ?>
로그인 후 복사

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('/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.

src/CakePHP 빠른 가이드/ElemsCakePHP 빠른 가이드.php

<?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

Output

Upon execution, the above URL will give you the following output.

Element Example

CakePHP - View Events

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.

CakePHP - Working with Database

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 −

My App

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 −

App Local

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
로그인 후 복사

Insert a Record

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.

Example

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

Output

Upon execution, you will receive the following output.

CakePHP 빠른 가이드

The data will be saved in the users table as shown below −

Show All

CakePHP - View a Record

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.

Example

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('/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.

src/controller/UsersCakePHP 빠른 가이드.php

<?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.

src/Template/Users/index.ctp

<a href="add">Add User</a>
로그인 후 복사
로그인 후 복사
로그인 후 복사
"; echo ""; echo ""; echo ""; endforeach; ?>
ID Username Password Edit Delete
".$row->id.""; echo " ".$row->password."EditDelete

Execute the above example by visiting the following URL http://localhost/cakephp4/users

Output

Upon execution, the above URL will give you the following output.

Upon Execution

CakePHP - Update a Record

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.

Example

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('/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.

src/controller/UsersCakePHP 빠른 가이드.php

<?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.

src/Template/Users/index.php

<a href="add">Add User</a>
로그인 후 복사
로그인 후 복사
로그인 후 복사
"; echo ""; echo ""; echo ""; echo ""; endforeach; ?>
ID Username Password Edit Delete
".$row->id."".$row->username."".$row->password."EditDelete

Create another View file under the Users directory called edit.php and copy the following code in it.

src/Template/Users/edit.php

<?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

Output

After visiting the above URL, it will display the records in users table as shown below −

After Visiting

Click on Edit button and it will display you following screen −

Edit Button

Now, we will update the name CakePHP 빠른 가이드 to CakePHP 빠른 가이드123 and submit the details. The next screen displayed will be as follows −

CakePHP 빠른 가이드

CakePHP - Delete a Record

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.

Example

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('/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.

src/controller/UsersCakePHP 빠른 가이드.php

<?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.

src/Template/Users/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.

src/Template/Users/index.ctp

<a href="add">Add User</a>
로그인 후 복사
로그인 후 복사
로그인 후 복사
"; echo ""; echo ""; echo ""; echo ""; endforeach; ?>
ID Username Password Edit Delete
".$row->id."".$row->username."".$row->password."EditDelete

Execute the above example by visiting the following URL and click on Delete link to delete record.

http://localhost:85/CakePHP/users

Output

After visiting the above URL and clicking on the Delete link, you will receive the following output where you can delete record.

Delete Link

Click on Delete link to delete the record.

User Deleted

CakePHP - Services

This chapter deals with the information about the authentication process available in CakePHP.

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.

Example for FormCakePHP 빠른 가이드

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

출력

인증이 구현되었기 때문에 위 URL로 접속을 시도하시면 아래와 같은 로그인 페이지로 이동하게 됩니다.

CakePHP 빠른 가이드

올바른 자격 증명을 입력하면 로그인되며 아래와 같은 화면으로 리디렉션됩니다.

CakePHP 빠른 가이드ed

로그아웃 링크를 클릭하면 다시 로그인 화면으로 이동합니다.

CakePHP - 오류 및 예외 처리

시스템의 원활한 운영을 위해서는 시스템 장애에 대한 효율적인 처리가 필요합니다. CakePHP에는 오류가 발생할 때 이를 인쇄하고 기록하는 기본 오류 추적 기능이 포함되어 있습니다. 동일한 오류 처리기가 예외를 포착하는 데 사용됩니다.

오류 핸들러는 디버그가 true인 경우 오류를 표시하고 디버그가 false인 경우 오류를 기록합니다. CakePHP에는 다양한 예외 클래스가 있으며 내장된 예외 처리 기능이 포착되지 않은 모든 예외를 캡처하여 유용한 페이지를 렌더링합니다.

오류 및 예외 구성

오류 및 예외는 configapp.php 파일에서 구성할 수 있습니다. 오류 처리에서는 애플리케이션에 맞게 오류 처리를 맞춤화할 수 있는 몇 가지 옵션을 허용합니다. −

를 구현해야 합니다.
옵션 데이터 유형 설명
오류레벨 정수
Option Data Type Description
errorLevel int

The level of errors you are interested in capturing. Use the built-in php error constants, and bitmasks to select the level of error you are interested in.

trace bool

Include stack traces for errors in log files. Stack traces will be included in the log after each error. This is helpful for finding where/when errors are being raised.

exceptionRenderer string

The class responsible for rendering uncaught exceptions. If you choose a custom class, you should place the file for that class in src/Error. This class needs to implement a render() method.

log bool

When true, exceptions + their stack traces will be logged to CakeLogLog.

skipLog array

An array of exception class names that should not be logged. This is useful to remove NotFoundExceptions or other common, but uninteresting logs messages.

extraFatalErrorMemory int

Set to the number of megabytes to increase the memory limit by, when a fatal error is encountered. This allows breathing room to complete logging or error handling.

캡처하려는 오류 수준입니다. 내장된 PHP 오류 상수와 비트마스크를 사용하여 관심 있는 오류 수준을 선택하세요.
추적 부울 로그 파일에 오류에 대한 스택 추적을 포함합니다. 각 오류 이후에는 스택 추적이 로그에 포함됩니다. 이는 언제 어디서 오류가 발생하는지 찾는 데 도움이 됩니다.
ExceptionRenderer 문자열 잡히지 않는 예외를 렌더링하는 클래스입니다. 사용자 정의 클래스를 선택하는 경우 해당 클래스에 대한 파일을 src/Error에 배치해야 합니다. 이 클래스는 render() 메소드
로그 부울 참인 경우 예외와 해당 스택 추적이 CakeLogLog에 기록됩니다.
skipLog 배열 기록하면 안 되는 예외 클래스 이름의 배열입니다. 이는 NotFoundExceptions 또는 기타 일반적이지만 흥미롭지 않은 로그 메시지를 제거하는 데 유용합니다.
extraFatalErrorMemory 정수 치명적인 오류가 발생한 경우 메모리 제한을 늘릴 메가바이트 수를 설정합니다. 이를 통해 로깅 또는 오류 처리를 완료할 여유가 있습니다.

Example

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('/exception/:arg1/:arg2',
      ['controller'=>'Exps','action'=>'index'],
      ['pass' => ['arg1', 'arg2']]);
   $builder->fallbacks();
});
로그인 후 복사

Create ExpsCakePHP 빠른 가이드.php file at src/CakePHP 빠른 가이드/ExpsCakePHP 빠른 가이드.php. Copy the following code in the controller file.

src/CakePHP 빠른 가이드/ExpsCakePHP 빠른 가이드.php

<?php namespace App\CakePHP 빠른 가이드;
   use App\CakePHP 빠른 가이드\AppCakePHP 빠른 가이드;
   use Cake\Core\Exception\Exception;
   class ExpsCakePHP 빠른 가이드 extends AppCakePHP 빠른 가이드 {
      public function index($arg1,$arg2) {
         try{
            $this->set('argument1',$arg1);
            $this->set('argument2',$arg2);
            if(($arg1 > 1 || $arg1 > 10) || ($arg2  10))
               throw new Exception("One of the number is out of range [1-10].");
         } catch(\Exception $ex){
            echo $ex->getMessage();
         }
      }
   }
?>
로그인 후 복사

Create a directory Exps at src/Template and under that directory create a View file called index.php. Copy the following code in that file.

src/Template/Exps/index.php

This is CakePHP tutorial and this is an example of Passed arguments.<br>
Argument-1: =$argument1?><br>
Argument-2: =$argument2?><br>
로그인 후 복사

Execute the above example by visiting the following URL.

http://localhost/cakephp4/exception/5/0

Output

Upon execution, you will receive the following output.

CakePHP 빠른 가이드

CakePHP - Logging

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provided by the LogTrait, which is the common ancestor for almost all CakePHP classes.

Logging Configuration

We can configure the log in file config/app.php. There is a log section in the file, where you can configure logging options as shown in the following screenshot.

CakePHP 빠른 가이드

By default, you will see two log levels − error and debug already configured for you. Each will handle different level of messages.

CakePHP supports various logging levels as shown below −

  • Emergency − System is unusable

  • Alert − Action must be taken immediately

  • Critical − Critical conditions

  • Error − Error conditions

  • Warning − Warning conditions

  • Notice − Normal but significant condition

  • Info − Informational messages

  • Debug − Debug-level messages

Writing to Log file

There are two ways by which, we can write in a Log file.

The first is to use the static write() method. The following is the syntax of the static write() method.

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()

Example

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

Output

Upon execution, you will receive the following output.

CakePHP 빠른 가이드

The logs will be added to log/debug.log file −

CakePHP 빠른 가이드

CakePHP - Form Handling

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
  • Elements to format

  • Parents for OPTGROUP

  • Whether to show parents

  • HTML attributes

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
  • The button's caption. Not automatically HTML encoded.

  • Array of options and HTML attributes

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
  • CakePHP 빠른 가이드 of a field, like this "Modelname.fieldname"

  • Array of HTML attributes. Possible options are value, checked, hiddenField, disabled, default.

Returns An HTML text input element.
Description Creates a checkbox input widget.

다음 기능은 HTML 페이지에서 양식을 작성하는 데 사용됩니다.

구문 생성( 혼합 $modelnull , 배열 $optionsarray() )
매개변수
  • Syntax create( mixed $modelnull , array $optionsarray() )
    Parameters
    • The model name for which the form is being defined. Should include the plugin name for plugin models. e.g. ContactManager.Contact. If an array is passed and $options argument is empty, the array will be used as options. If false, no model is used.

    • An array of html attributes and options. Possible options are type, action, url, default, onsubmit, inputDefaults, encoding.

    Returns

    A formatted opening FORM tag.

    Description Returns an HTML FORM element.
    양식이 정의되는 모델 이름입니다. 플러그인 모델의 플러그인 이름을 포함해야 합니다. 예를 들어 ContactManager.연락처. 배열이 전달되고 $options 인수가 비어 있으면 배열이 옵션으로 사용됩니다. false인 경우 모델이 사용되지 않습니다.
  • html 속성 및 옵션의 배열입니다. 가능한 옵션은 유형, 작업, URL, 기본값, 제출 시, inputDefaults, 인코딩입니다.

반품 형식이 지정된 시작 FORM 태그입니다.
설명 HTML FORM 요소를 반환합니다.
Syntax

file(string $fieldCakePHP 빠른 가이드, array $optionsarray() )

Parameters
  • CakePHP 빠른 가이드 of a field, in the form "Modelname.fieldname"

  • Array of HTML attributes.

Returns

A generated file input.

Description

Creates file input widget.

HTML 페이지에서
파일 업로드 기능

을 제공하기 위해 다음 기능을 사용합니다.

구문 파일(문자열 $fieldCakePHP 빠른 가이드, 배열 $optionsarray() )
매개변수
  • Syntax

    hidden( string $fieldCakePHP 빠른 가이드 , array $optionsarray() )

    Parameters
    • CakePHP 빠른 가이드 of a field, in the form of "Modelname.fieldname"

    • Array of HTML attributes.

    Returns

    A generated hidden input

    Description

    Creates a hidden input field

    "Modelname.fieldname" 형식의 필드 이름
  • HTML 속성 배열.

반품 생성된 파일 입력입니다.
설명
파일 입력 위젯을 생성합니다.
Syntax

Input(string $fieldCakePHP 빠른 가이드 , array $options array() )

Parameters
  • This should be "Modelname.fieldname"

  • Each type of input takes different options

Returns

Completed form widget

Description

Generates a form input element complete with label and wrapper div

다음 함수는 HTML 페이지에 숨겨진 요소를 생성하는 데 사용됩니다.

구문
Syntax

Radio(string $fieldCakePHP 빠른 가이드 , array $optionsarray() , array $attributesarray() )

Parameters
  • CakePHP 빠른 가이드 of a field, like this "Modelname.fieldname"

  • Radio button options array.

  • Array of HTML attributes, and special attributes above.

Returns Completed radio widget set
Description Creates a set of radio widgets. Will create a legend and fieldset by default. Use $options to control this.
숨김( 문자열 $fieldCakePHP 빠른 가이드 , 배열 $optionsarray() )
매개변수
  • "Modelname.fieldname" 형식의 필드 이름

  • HTML 속성 배열.
반품
생성된 숨겨진 입력
Syntax Submit(string $caption null, array $options array() )
Parameters
  • The label appearing on the button OR if string contains :// or the extension .jpg, .jpe, .jpeg, .gif, .png. Use an image if the extension exists, AND the first character is /, image is relative to webroot, OR if the first character is not /, image is relative to webroot/img.

  • Array of options. Possible options are div, before, after, type etc.

Returns

An HTML submit button

Description Creates a submit button element. This method will generate elements that can be used to submit, and reset forms by using $options. Image submits can be created by supplying an image path for $caption.
설명 숨겨진 입력 필드 생성
다음 함수는 HTML 페이지에서 입력 요소를 생성하는 데 사용됩니다.
구문 입력(문자열 $fieldCakePHP 빠른 가이드 , 배열 $options array() )
매개변수
  • "Modelname.fieldname"이어야 합니다
  • 입력 유형마다 다른 옵션이 필요합니다
반품 완성된 양식 위젯
설명 라벨 및 래퍼 div가 포함된 양식 입력 요소를 생성합니다
다음 함수는 HTML 페이지에서 라디오 버튼을 생성하는 데 사용됩니다.
구문 Radio(문자열 $fieldCakePHP 빠른 가이드 , 배열 $optionsarray() , 배열 $attributesarray() ) TD>
매개변수
  • 필드 이름(예: "Modelname.fieldname")
  • 라디오 버튼 옵션 배열.
  • HTML 속성 배열 및 위의 특수 속성.
반품 완성된 라디오 위젯 세트
설명 라디오 위젯 세트를 만듭니다. 기본적으로 범례와 필드 세트를 생성합니다. 이를 제어하려면 $options를 사용하세요.
다음 함수는 HTML 페이지에 제출 버튼을 생성하는 데 사용됩니다.
구문 제출(string $caption null, 배열 $options array() )
매개변수
  • 버튼에 표시되는 라벨 또는 문자열에 :// 또는 확장자 .jpg, .jpe, .jpeg, .gif, .png가 포함된 경우. 확장명이 존재하고 첫 번째 문자가 /이고 이미지가 webroot에 상대적인 경우 또는 첫 번째 문자가 /가 아닌 경우 이미지가 webroot/img에 상대적인 경우 이미지를 사용하세요.
  • 옵션 배열. 가능한 옵션은 div, before, after, type 등입니다.
반품 HTML 제출 버튼
설명 제출 버튼 요소를 생성합니다. 이 메소드는 $options를 사용하여 양식을 제출하고 재설정하는 데 사용할 수 있는 요소입니다. $caption에 대한 이미지 경로를 제공하여 이미지 제출을 생성할 수 있습니다.

The following functions are used to generate textarea element on HTML page.

Syntax

Textarea(string $fieldCakePHP 빠른 가이드 , array $options array() )

Parameters
  • CakePHP 빠른 가이드 of a field, in the form "Modelname.fieldname"

  • Array of HTML attributes, special option like escape

Returns A generated HTML text input element
Description Creates a textarea widget

Example

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 &mp; 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

Output

Upon execution, you will receive the following output.

CakePHP 빠른 가이드

CakePHP - Internationalization

Like many other frameworks, CakePHP also supports Internationalization. We need to follow these steps to go from single language to multiple language.

Step 1

Create a separate locales directory resources\locales.

Step 2

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.

Step 3

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.

Step 4

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');
로그인 후 복사

Example

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

Output

Upon execution, you will receive the following output.

CakePHP 빠른 가이드

Email

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
  • String with email

  • CakePHP 빠른 가이드

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
  • String with email

  • CakePHP 빠른 가이드

Returns

array|$this

Description

It specifies to whom the email will be sent

Syntax

Send(string|array|null $contentnull)

Parameters
  • String with message or array with messages.

Returns array
Description

Send an email using the specified content, template and layout

Syntax

Subject(string|null $subjectnull)

Parameters
  • Subject string

Returns

array|$this

Description

Get/Set Subject

Syntax

Attachments(string|array|null $attachmentsnull)

Parameters
  • String with the filename or array with filenames

Returns

array|$this

Description

Add attachments to the email message

Syntax

Bcc(string|array|null $emailnull, string|null $namenull)

Parameters
  • String with email

  • CakePHP 빠른 가이드

Returns

array|$this

Description

Bcc

Syntax

cc( string|array|null $emailnull , string|null $namenull )

Parameters
  • String with email

  • CakePHP 빠른 가이드

Returns

array|$this

Description

Cc

Example

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

Program App

Execute the above example by visiting the following URL − http://localhost/cakephp/email

Output

Upon execution, you will receive the following output.

Documents Api

CakePHP - Session Management

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.

Accessing Session Object

Session object can be created by executing the following code.

$session = $this->request->session();
로그인 후 복사

Writing Session Data

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.

Example

$session->write('name', 'CakePHP 빠른 가이드 Gandhi');
로그인 후 복사

Reading Session Data

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.

Example

$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.

Example

if ($session->check('name')) {
   // name exists and is not null.
}
로그인 후 복사

Delete Session Data

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.

Example

$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.

Example

$session->consume('name');
로그인 후 복사

Destroying a Session

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()
로그인 후 복사

Example

$session->destroy();
로그인 후 복사

Destroying session will remove all session data from server, but will not remove session cookie.

Renew a Session

In a situation, where you want to renew user session then, we can use the renew() session method.

Session::renew()
로그인 후 복사

Example

$session->renew();
로그인 후 복사

Complete Session

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 빠른 가이드.
로그인 후 복사

Output

Execute the above example by visiting the following URL. This URL will help you write data in session.

http://localhost/cakephp4/session-write

Written in Session

Visit the following URL to read session data − http://localhost/cakephp4/session-read

CakePHP 빠른 가이드

Visit the following URL to check session data − http://localhost/cakephp4/session-check

CakePHP 빠른 가이드 Exists

Visit the following URL to delete session data − http://localhost/cakephp4/session-delete Visit the

Delete From Session

Visit the following URL to destroy session data − http://localhost/cakephp4/session-destroy

CakePHP 빠른 가이드

CakePHP - CakePHP 빠른 가이드 Management

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.

Write CakePHP 빠른 가이드

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);
로그인 후 복사

Read CakePHP 빠른 가이드

To read cookie make use of get() method from cookiecollection.

Syntax

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()
로그인 후 복사

Check CakePHP 빠른 가이드

The has() method from cookieCollection will tell you, if the cookie is present or not.

Cake\Http\CakePHP 빠른 가이드\CakePHP 빠른 가이드Collection::has($name)
로그인 후 복사

Example

echo $isPresent = $this->cookies->has('name');
로그인 후 복사

Delete CakePHP 빠른 가이드

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.

Example 1

$test = $this->cookies->remove('name');
로그인 후 복사

Example 2

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;
?>
로그인 후 복사

Output

Execute the above example by visiting the following URL − http://localhost/cakephp4/cookie/testcookies

CakePHP 빠른 가이드

CakePHP - Security

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.

Encryption and Decryption

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

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

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.

Example

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

Output

Upon execution, you will receive the following output.

Submit Login

CakePHP - Validation

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.

Validation Methods

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
  • The name of the field from which the rule will be added.

  • The alias for a single rule or multiple rules array.

  • The rule to add

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
  • The name of the field.

  • Indicates when the field is allowed to be empty. Valid values are true (always), 'create', 'update'. If a callable is passed, then the field will be left empty only when the callback returns true.

  • The message to show if the field is not.

Returns $this
Description

Allows a field to be empty.

Syntax

alphanumeric (string $field, string|null $messagenull, string|callable|null $whennull)

Parameters
  • The field you want to apply the rule to.

  • The error message when the rule fails.

  • Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.

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
  • The field you want to apply the rule to.

  • The type of cards you want to allow. Defaults to 'all'. You can also supply an array of accepted card types, for example, ['mastercard', 'visa', 'amex'].

  • The error message when the rule fails.

  • Either 'create' or 'update' or a callable that returns true, when the validation rule should be applied.

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
  • The field you want to apply the rule to.

  • Whether or not to check the MX records.

  • The error message when the rule fails.

  • Either 'create' or 'update' or a callable that returns true, when the validation rule should be applied.

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
  • The field you want to apply the rule to.

  • The maximum length allowed.

  • The error message when the rule fails.

  • Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.

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
  • The field you want to apply the rule to.

  • The maximum length allowed.

  • The error message when the rule fails.

  • Either 'create' or 'update' or a callable, that returns true when the validation rule should be applied.

Returns

$this

Description

Add a string length validation rule to a field.

Syntax

notBlank(string $field, string|null $messagenull, string|callable|null $whennull)

Parameters
  • The field you want to apply the rule to.

  • The error message when the rule fails.

  • Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.

Returns

$this

Description

Add a notBlank rule to a field.

CakePHP - Creating Validators

Validator can be created by adding the following two lines in the controller.

use Cake\Validation\Validator;
$validator = new Validator();
로그인 후 복사

Validating Data

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.

Example

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

Output

Click on the submit button without entering anything. You will receive the following output.

Click PHP

Http - Client

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.

HTTP GET Method

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()
로그인 후 복사

Example

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
로그인 후 복사

Output

Click on the submit button without entering anything. You will receive the following output.

Users URL

HTTP POST Method

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.

Example

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

Output

Given below is the output of the code −

Post Method

Similarly, you can try for PUT method.

$http = new Client();
$response = $http->put('https://postman-echo.com/post', [
   'name'=> 'ABC',
   'email' => 'xyz@gmail.com'
]);
로그인 후 복사

CakePHP - Pagination

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 −

CakePHP 빠른 가이드

Let us use pagination to display the data in the form of pages, instead of showing them all together.

Example

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('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.

src/CakePHP 빠른 가이드/PostsCakePHP 빠른 가이드.php

<?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.

src/Template/Posts/index.php

<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 −

로그인 후 복사
    = $this->Paginator->prev(" = $this->Paginator->numbers() ?> = $this->Paginator->next(">>") ?>

Execute the above example by visiting the following URL −

http://localhost/cakephp4/posts

Output

When you run the code, you will see the following output −

CakePHP 빠른 가이드

Click on the numbers below, to switch to next page, or use the next or previous button.

For example

CakePHP 빠른 가이드1

You will see that page=2 is appended to the page url in the browser.

CakePHP - Date and Time

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.

Example

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('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.

src/CakePHP 빠른 가이드/DatesCakePHP 빠른 가이드.php

<?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.

src/Template/Dates/index.php

<?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

Output

When you run the code, you will see the following output −

Current Date

CakePHP - File upload

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Example

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('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.

src/CakePHP 빠른 가이드/FilesCakePHP 빠른 가이드.php

<?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.

src/Template/Files/index.php

<?php echo $this->Form->create(NULL, ['type' => 'file']);
   echo $this-&gtl;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 −

Output

When you execute the above code, you should see the following output −

Choose File

위 내용은 CakePHP 빠른 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿