Validator can be created by adding the following two lines in the controller.
use Cake\Validation\Validator; $validator = new Validator();
Once, we have created validator, we can use the validator object to validate data. The following code explains, how we can validate data for login webpage.
$validator->notEmpty('username', 'We need username.')->add( 'username', 'validFormat', ['rule' => 'email','message' => 'E-mail must be valid']); $validator->notEmpty('password', 'We need password.'); $errors = $validator->errors($this->request->data());
Using the $validator object, we have first called the notEmpty() method, which will ensure that the username must not be empty. After that, we have chained the add() method to add one more validation for proper email format.
After that we have added validation for password field with notEmpty() method, which will confirm that password field must not be empty.
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('validation',['controller'=>'Valids','action'=>'index']); $builder->fallbacks(); });
Create a ValidsController.php file at src/Controller/ValidsController.php. Copy the following code in the controller file.
src/Controller/ValidsController.php
<?php namespace App\Controller; use App\Controller\AppController; use Cake\Validation\Validator; class ValidsController extends AppController{ 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.'</font><br>'; } else { echo "No errors."; } echo $this->Form->create(NULL,array('url'=>'/validation')); echo $this->Form->control('username'); echo $this->Form->control('password'); echo $this->Form->button('Submit'); echo $this->Form->end(); ?>
Execute the above example by visiting the following URL −
http://localhost/cakephp4/validation
Click on the submit button without entering anything. You will receive the following output.
The http client can be used to make requests like GET, POST, PUT etc.
To work with http client, add the following −
use Cake\Http\Client;
Let us work on example to understand working of HTTP client.
To get the data from give http url, you can do as follows −
$response = $http->get('https://jsonplaceholder.typicode.com/users');
In case, you need to pass some query params, they can be passed as follows −
$response = $http->get('https://jsonplaceholder.typicode.com/users', ["id", 1]);
To get the response, you can do as follows −
For normal text data −
$response->getBody();
For Json −
$response->getJson();
For Xml −
$response->getXml()
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('getData',['controller'=>'Requests','action'=>'index']); $builder->fallbacks(); });
Create a RequestsController.php file at src/Controller/RequestsController.php. Copy the following code in the controller file.
src/Controller/RequestsController.php
<?php namespace App\Controller; use App\Controller\AppController; use Cake\Http\Client; class RequestsController extends AppController{ 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">Name: '.$val["name"].' Email -'.$val["email"].'</font><br>'; } } ?>
Execute the above example by visiting the following URL −
http://localhost/cakephp4/getData
Click on the submit button without entering anything. You will receive the following output.
To work with post, you need to call $http client as follows −
$response = $http->post('yoururl', data);
Let us see one example on the same.
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('postData',['controller'=>'Requests','action'=>'index']); $builder->fallbacks(); });
Create a RequestsController.php file at src/Controller/RequestsController.php. Copy the following code in the controller file. Ignore if already created.
src/Controller/RequestsController.php
<?php namespace App\Controller; use App\Controller\AppController; use Cake\Http\Client; class RequestsController extends AppController{ public function index(){ $http = new Client(); $response = $http->post('https://postman-echo.com/post', [ 'name'=> 'ABC', 'email' => 'xyz@gmail.com' ]); } } ?>
Create a directory Requests at src/Template and under that directory create a View file called index.php. Copy the following code in that file.
src/Template/Requests/index.php
<h3>Testing Post Method</h3>
Execute the above example by visiting the following URL −
http://localhost/cakephp4/postData
Given below is the output of the code −
Similarly, you can try for PUT method.
$http = new Client(); $response = $http->put('https://postman-echo.com/post', [ 'name'=> 'ABC', 'email' => 'xyz@gmail.com' ]);
The above is the detailed content of CakePHP Creating Validators. For more information, please follow other related articles on the PHP Chinese website!