CakePHP – Creating Validators

CakePHP – Creating Validators ”; Previous Next Validator can be created by adding the following two lines in the controller. use CakeValidationValidator; $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 CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $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 AppController; use AppControllerAppController; use CakeValidationValidator; 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 Output Click on the submit button without entering anything. You will receive the following output. 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 CakeHttpClient; 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 CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $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 AppController; use AppControllerAppController; use CakeHttpClient; 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 Output Click on the submit button without entering anything. You will receive the following output. 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 CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $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 AppController; use AppControllerAppController; use CakeHttpClient; class RequestsController extends AppController{ public function index(){ $http = new Client(); $response = $http->post(”https://postman-echo.com/post”, [ ”name”=> ”ABC”, ”email” => ”[email protected]” ]); } } ?> 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 − Similarly, you can try for PUT method. $http = new Client(); $response = $http->put(”https://postman-echo.com/post”, [ ”name”=> ”ABC”, ”email” => ”[email protected]” ]); Print Page Previous Next Advertisements ”;

CakePHP – Views

CakePHP – Views ”; Previous Next 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 (ProductsController) is same as the name of the folder (Products) but without the word Controller and name of action/method (view()) of the controller (ProductsController) is same as the name of the View file(view.php). View Variables 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. CakeViewView::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 CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $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 ProductsController.php file at src/Controller/ProductsController.php. Copy the following code in the controller file. src/Controller/ProductsController.php <?php declare(strict_types=1); namespace AppController; use CakeCoreConfigure; use CakeHttpExceptionForbiddenException; use CakeHttpExceptionNotFoundException; use CakeHttpResponse; use CakeViewExceptionMissingTemplateException; class ProductsController extends AppController { public function view(){ $this->set(”Product_Name”,”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_Name; ? > Execute the above example by visiting the following URL. http://localhost/cakephp4/template Output The above URL will produce the following output. Print Page Previous Next Advertisements ”;

CakePHP – Discussion

Discuss CakePHP ”; Previous Next CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers guarantee a strict, but natural separation of business logic from data and presentation layers. Print Page Previous Next Advertisements ”;

CakePHP – File upload

CakePHP – File upload ”; Previous Next 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 CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $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 FilesController.php file at src/Controller/FilesController.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/Controller/FilesController.php <?php namespace AppController; use AppControllerAppController; use CakeViewHelperFormHelper; class FilesController extends AppController { 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 < count($files); $i++) echo “File is – “.$files[$i].”<br>”; ?> 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 − Print Page Previous Next Advertisements ”;

CakePHP – Update a Record

CakePHP – Update a Record ”; Previous Next 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 CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $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 UsersController.php file at src/Controller/UsersController.php. Copy the following code in the controller file. src/controller/UsersController.php <?php namespace AppController; use AppControllerAppController; use CakeORMTableRegistry; use CakeDatasourceConnectionManager; class UsersController extends AppController{ 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> <table> <tr> <td>ID</td> <td>Username</td> <td>Password</td> <td>Edit</td> <td>Delete</td> </tr> <?php foreach ($results as $row): echo “<tr><td>”.$row->id.”</td>”; echo “<td>”.$row->username.”</td>”; echo “<td>”.$row->password.”</td>”; echo “<td><a href=””.$this->Url->build([“controller” => “Users”,”action” => “edit”,$row->id]).””>Edit</a></td>”; echo “<td><a href=””.$this->Url->build([“controller” => “Users”,”action” => “delete”,$row->id]).””>Delete</a></td></tr>”; endforeach; ?> </table> 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 − Click on Edit button and it will display you following screen − Now, we will update the name Virat to Virat123 and submit the details. The next screen displayed will be as follows − Print Page Previous Next Advertisements ”;

CakePHP – Useful Resources

CakePHP – Useful Resources ”; Previous Next The following resources contain additional information on CakePHP. Please use them to get more in-depth knowledge on this. Useful Video Courses PHP Programming Online Training Most Popular 46 Lectures 9 hours Tutorialspoint More Detail PHP from Scratch Full Course 18 Lectures 1 hours Nivedita Jain More Detail Full Stack Web Development – HTML, CSS, JavaScript, PHP, ELIXIR 55 Lectures 6 hours Pranjal Srivastava, Harshit Srivastava More Detail Java, PHP and MySQL Course Bundle 53 Lectures 6 hours Harshit Srivastava More Detail Learn PHP – For Beginners 31 Lectures 1.5 hours YouAccel More Detail JavaScript, Bootstrap, and PHP – Training for Beginners 117 Lectures 5.5 hours YouAccel More Detail Print Page Previous Next Advertisements ”;

CakePHP – Internationalization

CakePHP – Internationalization ”; Previous Next 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 resourceslocales. Step 2 Create subdirectory for each language, under the directory srcLocale. 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 CakeI18nI18n; I18n::locale(”de_DE”); Example Make changes in the config/routes.php file as shown in the following program. config/routes.php <?php use CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $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 LocalizationsController.php file at src/Controller/LocalizationsController.php. Copy the following code in the controller file. src/Controller/LocalizationsController.php <?php namespace AppController; use AppControllerAppController; use CakeI18nI18n; class LocalizationsController extends AppController { public function index() { if($this->request->is(”post”)) { $locale = $this->request->getData(”locale”); I18n::setLocale($locale); } } } ?> Create a locales directory at resourceslocales. 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 <?php echo $this->Form->create(NULL,array(”url”=>”/locale”)); echo $this->Form->radio(“locale”, [ [”value”=>”en_US”,”text”=>”English”], [”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. 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 CakeMailerEmail; 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 Name 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 Name 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 Name Returns array|$this Description Bcc Syntax cc( string|array|null $emailnull , string|null $namenull ) Parameters String with email Name 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 CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $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 EmailsController.php file at src/Controller/EmailsController.php. Copy the following code in the controller file. src/Controller/EmailsController.php <?php namespace AppController; use AppControllerAppController; use CakeMailerEmail; class EmailsController extends AppController{ public function index(){ $email = new Email(”default”); $email->to(”[email protected]”) ->subject(”About”) ->send(”My message”); } } ?> Create a directory Emails at src/Template and under that directory, create a View file called index.php. Copy the following code in that file. src/Template/Emails/index.php Email Sent. Before we send any email, we need to configure it. In the below screenshot, you can see that there are two transports, default and Gmail. We have used Gmail transport. You need to replace the “GMAIL USERNAME” with your Gmail username and “APP PASSWORD” with your applications password. You need to turn on 2-step verification in Gmail and create a new APP password to send email. config/app.php Execute the above example by visiting the following URL − http://localhost/cakephp/email Output Upon execution, you will receive the following output. Print Page Previous Next Advertisements ”;

CakePHP – View Elements

CakePHP – View Elements ”; Previous Next 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. CakeViewView::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 CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $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 ElemsController.php file at src/Controller/ElemsController.php. Copy the following code in the controller file. src/Controller/ElemsController.php <?php namespace AppController; use AppControllerAppController; class ElemsController extends AppController{ 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. Print Page Previous Next Advertisements ”;

CakePHP – Validation

CakePHP – Validation ”; Previous Next 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|CakeValidationValidationRule $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. Print Page Previous Next Advertisements ”;

CakePHP – Controllers

CakePHP – Controllers ”; Previous Next The controller as the name indicates controls the application. It acts like a bridge between models and views. Controllers 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 Controller class names are in plural form, Camel Cased, and end in Controller — PostsController. AppController The AppConttroller class is the parent class of all applications’ controllers. This class extends the Controller class of CakePHP. AppController is defined at src/Controller/AppController.php. The file contains the following code. <?php declare(strict_types=1); namespace AppController; use CakeControllerController; class AppController extends Controller { public function initialize(): void { parent::initialize(); $this->loadComponent(”RequestHandler”); $this->loadComponent(”Flash”); } } AppController can be used to load components that will be used in every controller of your application. The attributes and methods created in AppController 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. Controller 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 RecipesController extends AppController { 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 RecipesController has 3 actions − View, Share, and Search. Redirecting 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. CakeControllerController::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 CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $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”=>”Redirects”,”action”=>”action1”]); $builder->connect(”/redirect-controller2”,[”controller”=>”Redirects”,”action”=>”action2”]); $builder->fallbacks(); }); Create a RedirectsController.php file at src/Controller/RedirectsController.php. Copy the following code in the controller file. src/Controller/RedirectsController.php <?php declare(strict_types=1); namespace AppController; use CakeCoreConfigure; use CakeHttpExceptionForbiddenException; use CakeHttpExceptionNotFoundException; use CakeHttpResponse; use CakeViewExceptionMissingTemplateException; class RedirectsController extends AppController { public function action1() { } public function action2(){ echo “redirecting from action2″; $this->setAction(”action1”); } } Create a directory Redirects at src/Template and under that directory create a View file called action1.php. Copy the following code in that file. src/Template/Redirects/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. Now, visit the following URL: http://localhost/cakephp4/redirect-controller2 The above URL will give you the following output. Loading Models In CakePHP, a model can be loaded using the loadModel() method. The following is the syntax for the loadModel() method − CakeControllerController::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 Articles model in a controller, then it can be loaded by writing the following line in controller’s action. $this->loadModel(”Articles”); Print Page Previous Next Advertisements ”;