Tutorials on How to Install CakePHP

Tutorials on How to Install CakePHP

Installing CakePHP is simple and easy. You can install it from composer or you can download it from github − https://github.com/cakephp/cakephp/releases. We will further understand how to install CakePHP in WampServer. After downloading it from github, extract all the files in a folder called “CakePHP” in WampServer. You can give custom name to folder but we have used “CakePHP”.

CakePHP has a few system requirements:

  • HTTP Server. For example: Apache. Having mod_rewrite is preferred, but by no means required. You can also use nginx, or Microsoft IIS if you prefer.
  • PHP 5.6.0 or greater (including PHP 7.3).
  • mbstring PHP extension
  • intl PHP extension
  • simplexml PHP extension
  • PDO PHP extension

 

While a database engine isn’t required, we imagine that most applications will utilize one. CakePHP supports a variety of database storage engines:

  • MySQL (5.5.3 or greater)
  • MariaDB (5.5 or greater)
  • PostgreSQL
  • Microsoft SQL Server (2008 or higher)
  • SQLite 3

Installing CakePHP

Before starting you should make sure that your PHP version is up to date:

php -v

You should have PHP 5.6.0 (CLI) or higher. Your webserver’s PHP version must also be of 5.6.0 or higher, and should be the same version your command line interface (CLI) uses.

Installing Composer

CakePHP uses Composer, a dependency management tool, as the officially supported method for installation.

  • Installing Composer on Linux and macOS

    1. Run the installer script as described in the official Composer documentation and follow the instructions to install Composer.

    2. Execute the following command to move the composer.phar to a directory that is in your path:

      mv composer.phar /usr/local/bin/composer
      
  • Installing Composer on Windows

    For Windows systems, you can download Composer’s Windows installer here. Further instructions for Composer’s Windows installer can be found within the README here.

 

cakephp starting project
CakePHP starting a Project with Command

After a successful installation of cakephp run the server to see the setting information about the application

Read the official CakePHP Installation Document

Folder Structure Overview in CakePHP

Folder Structure Overview in CakePHP

CakePHP – Folder Structure

The following table describes the role of each folder −

S.No Folder Name & Description
1 bin

The bin folder holds the Cake console executables.

2 config

The config folder holds the (few) configuration files CakePHP uses. Database connection details, bootstrapping, core configuration files and more should be stored here.

3 logs

The logs folder normally contains your log files, depending on your log configuration.

4 plugins

The plugins folder is where the Plugins your application uses are stored.

5 src

The src folder will be where you work your magic: It is where your application’s files will be placed. CakePHP’s src folder is where you will do most of your application development. Let’s look a little closer at the folders inside src.

  • Console Contains the console commands and console tasks for your application.
  • Controller Contains your application’s controllers and their components.
  • Locale Stores string files for internationalization.
  • Model Contains your application’s tables, entities and behaviors.
  • View Presentational classes are placed here: cells, helpers, and template files.
  • Template Presentational files are placed here: elements, error pages, layouts, and view template files.
6 tests

The tests folder will be where you put the test cases for your application.

7 tmp

The tmp folder is where CakePHP stores temporary data. The actual data it stores depends on how you have CakePHP configured, but this folder is usually used to store model descriptions and sometimes session information.

8 vendor

The vendor folder is where CakePHP and other application dependencies will be installed. Make a personal commitment not to edit files in this folder. We can’t help you if you’ve modified the core.

9 webroot

The webroot directory is the public document root of your application. It contains all the files you want to be publically reachable.

 

How to Extend Views in CakePHP

Extend Views in CakePHP

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 CakeCorePlugin; 
use CakeRoutingRouteBuilder; 
use CakeRoutingRouter; 
Router::defaultRouteClass('DashedRoute'); 
Router::scope('/', function (RouteBuilder $routes) { $routes->connect('extend',['controller'=>'Extends','action'=>'index']); $routes->fallbacks('DashedRoute'); }); 
Plugin::routes();

Create a ExtendsController.php file at src/Controller/ExtendsController.php. Copy the following code in the controller file.

src/Controller/ExtendsController.php

<?php namespace AppController; use AppControllerAppController; class ExtendsController extends AppController{ public function index(){ } } ?>

Create a directory Extends at src/Template and under that folder create a View file called header.ctp. Copy the following code in that file.

src/Template/Extends/header.ctp

Common Header

<?= $this->fetch('content') ?>

Create another View under Extends directory called index.ctp. Copy the following code in that file. Here we are extending the above view header.ctp.

src/Template/Extends/index.ctp

<?php $this->extend('header'); ?>

This is an example of extending view.

Execute the above example by visiting the following URL.

http://localhost:85/CakePHP/extend

Output

Upon execution, you will receive the following output.

 

How to Handle Errors and Exception in CakePHP

How to Handle Errors and Exception in CakePHP

Failure of system needs to be handled effectively for smooth running of the system. CakePHP comes with default error trapping that prints and logs error as they occur. This same error handler is used to catch Exceptions. Error handler displays errors when debug is true and logs error when debug is false. CakePHP has number of exception classes and the built in exception handling will capture any uncaught exception and render a useful page.

Errors and Exception Configuration

Errors and Exception can be configured in file configapp.php. Error handling accepts a few options that allow you to tailor error handling for your application −

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

Example

Make changes in the config/routes.php file as shown in the following code.

config/routes.php

<?php use CakeCorePlugin; 
use CakeRoutingRouteBuilder; 
use CakeRoutingRouter; 
Router::defaultRouteClass('DashedRoute'); 
Router::scope('/', 
function (RouteBuilder $routes) { $routes->connect('/exception/:arg1/:arg2',[ 'controller'=>'Exps','action'=>'index'],['pass' => ['arg1', 'arg2']]); $routes->fallbacks('DashedRoute'); }); 
Plugin::routes();

Create ExpsController.php file at src/Controller/ExpsController.php. Copy the following code in the controller file.

src/Controller/ExpsController.php

<?php namespace AppController; 
use AppControllerAppController; 
use CakeCoreExceptionException; 
class ExpsController extends AppController{ public function index($arg1,$arg2){ try{ $this->set('argument1',$arg1); $this->set('argument2',$arg2); 
if(($arg1 < 1 || $arg1 > 10) || ($arg2 < 1 || $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.ctp. Copy the following code in that file.

src/Template/Exps/index.ctp

This is CakePHP tutorial and this is an example of Passed arguments. Argument-1: <?=$argument1?> Argument-2: <?=$argument2?>

Execute the above example by visiting the following URL.

http://localhost:85/CakePHP/exception/5/0

Discuss on CakePHP Framework

Discuss on CakePHP Framework

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

CakePHP can be asked and both the community and core developers will get a chance to help and contribute. Please keep discussion friendly and constructive. Click here to join in CakePHP Official Forum

Cakephp official website: https://book.cakephp.org

How to Delete Records from Database Table in CakePHP

Delete Records from Database Table in CakePHP

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 CakeCorePlugin;
use CakeRoutingRouteBuilder;
use CakeRoutingRouter;
Router::defaultRouteClass(‘DashedRoute’);
Router::scope(‘/’, function (RouteBuilder $routes) { $routes->connect(‘/users/delete’,
[‘controller’ => ‘Users’, ‘action’ => ‘delete’]); $routes->fallbacks(‘DashedRoute’); });
Plugin::routes();

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 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 View file called index.ctp. Copy the following code in that file.

src/Template/Users/index.ctp

Add User

 

ID Username Password Edit Delete

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

http://localhost:85/CakePHP/users

How to Create Validators in CakePHP

Create Validators in CakePHP

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 confirms 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 CakeCorePlugin; use CakeRoutingRouteBuilder; use CakeRoutingRouter; Router::defaultRouteClass(‘DashedRoute’); Router::scope(‘/’, function (RouteBuilder $routes) { $routes->connect(‘validation’,[‘controller’=>’Valids’,’action’=>’index’]); $routes->fallbacks(‘DashedRoute’); }); Plugin::routes();

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->data()); $this->set(‘errors’,$errors); } } ?>

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

src/Template/Valids/index.ctp

<?php if($errors){ foreach($errors as $error) foreach($error as $msg) echo ‘<font color = “red”>’.$msg.'</font&gtl’; } else { echo “No errors.”; } echo $this->Form->create(“Logins”,array(‘url’=>’/validation’)); echo $this->Form->input(‘username’); echo $this->Form->input(‘password’); echo $this->Form->button(‘Submit’); echo $this->Form->end(); ?>

Execute the above example by visiting the following URL −http://localhost:85/CakePHP/validation

Output

Click on the submit button without entering anything.