CakePHP 4 Tutorial for Beginners Part-1 How to Install CakePHP 4


 

CakePHP is an open source web application framework. It follows the Model-View-Controller (MVC) approach and written in PHP. CakePHP makes building web applications simpler, faster and require less code.

This CakePHP tutorial will drive you to the right direction for getting started with CakePHP framework and provide basic guide of CakePHP application development. Our step by step CakePHP tutorial helps beginners for install and configures the CakePHP application. You can learn CakePHP from scratch with our easy tutorial. Also we will develop a sample CakePHP project and it will help you for better understanding the whole process.
You must have PHP 7.2 higher. The PHP version of your web server must be at least 7.2 or higher and the same version that the command line interface (CLI) uses.

Installing Composer

Installing composer on Windows in the official composer documentation and follow the instructions to install composer.

Create a CakePHP Project

You can create a new CakePHP application using the create-project creator command:
composer create-project --prefer-dist cakephp/app:~4.0 your_project_name
Hit this command in command prompt and download CakePHP 4 in our xampphtdocs directory and change folder name with your desire project name.

CakePHP Folder and Structure 

/your_project_name/
bin/
config/
logs/
plugins/
resources/
src/
templates/
tests/
tmp/
vendor/
webroot/ (this directory is set as DocumentRoot)
.gitignore
.htaccess
.travis.yml
composer.json
index.php
phpunit.xml.dist
README.md

Basic Configuration

Step-1 Create database at the localhost/phpmyadmin. For example blog_database.
Step-2 Open the “config/app_local.php” file and make the following changes.
Go to the Datasources section and replace the value of host to localhost, username to root, password to our blank if you have and database name.
<?php
return [
// More configuration above.
'Datasources' => [
'default' => [
'className' => 'CakeDatabaseConnection',
// Replace Mysql with Postgres if you are using PostgreSQL
'driver' => 'CakeDatabaseDriverMysql',
'persistent' => false,
'host' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'your_database_name',
// Comment out the line below if you are using PostgreSQL
'encoding' => 'utf8mb4',
'timezone' => 'UTC',
'cacheMetadata' => true,
],
],
// More configuration below.
];

 

Step-3 Run the project URL http://localhost/cakephp4/   at the browser 

CakePHP 4 Tutorial for Beginners

CakePHP Naming Conventions

Model Convention: Model class names are singular Camel Based Admin and Product 
Controller Convention: Controller class names are plural, Camel Based and end in Controller
as ProductsController, AdminsController

View Convention: The template view files are named in the controller function, which are shown in underscored form. The index() function of the ProductsController class looks for a view template in template/Products/index.php. The base model is src/Model/Entity & Table/Product.php & ProductsTable.php.

Create a Simple Application with CakePHP 4.x

We will build a sample application using CakePHP 4.x. This sample app pulls multiple publications from the database, displays data for those publications, and displays them in the browser.

Create a Posts Table

--
-- Table structure for table `posts`
--
CREATE TABLE `posts` (
`id` int(100) NOT NULL,
`title` varchar(100) NOT NULL,
`description` varchar(100) NOT NULL,
`created` datetime NOT NULL,
`updated` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Create a Posts Controller

We will create a controller in src/Controller/PostsController.php. Here’s what the Posts Controller is look like.
<?php

// src/Controller/PostsController.php

namespace AppController;
use AppControllerAppController;
use CakeEventEventInterface;
use CakeDatasourceFactoryLocator;

class PostsController extends AppController{

public $postsTableObj;

public function beforefilter(EventInterface $event){
    parent::beforefilter($event);
    $this->postsTableObj = FactoryLocator::get('Table')->get('Posts');
}


public function index(){
$this->loadComponent('Paginator');
$posts = $this->Paginator->paginate($this->postsTableObj->find());
$this->set(compact('posts'));
}

}

Create Posts Model 

We are create Posts Table in Model folder src/Model/Table/PostsTable.php for the validation of the posts form using CakePHP validation.
<?php

namespace AppModelTable;
use CakeORMTable;
use CakeValidationValidator;



class PostsTable extends Table
{
public function initialize(array $config): void
{
$this->addBehavior('Timestamp', [
'events' => [
'Model.beforeSave' => [
'created' => 'new',
'updated' => 'always'
]
]
]);
}



public function validationDefault(Validator $validator): Validator
{

$validator
->notEmptyString('title')
->notEmptyString('description');
return $validator;
}

}

Create Posts View

CakePHP template files are stored in the templates directory. In this directory we need to create a folder called “posts” and create an index.php file. Our display code is shown below:
<div class="container">
<div class="row">
<div class="col-md-12">
<h2 class="text-center" style="margin-top:50px;">Posts View</h2>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Created</th>
<th>Updated</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($posts as $post) { ?>
<tr>
<td><?php echo $post->id ?></td>
<td><?php echo $post->title ?></td>
<td><?php echo $post->description ?></td>
<td><?php echo date('d-M-Y', strtotime($post->created)) ?></td>
<td><?php echo date('d-M-Y', strtotime($post->updated)) ?></td>
<td>
<a href="<?php echo $this->Url->build(['controller'=>'Posts', 'action'=>'edit', $post->id]) ?>">Edit</a>
<a href="<?php echo $this->Url->build(['controller'=>'Posts', 'action'=>'delete', $post->id]) ?>"
onclick="return confirm('Are you sure you want to delete this item?');">
Delete</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>

</div>

Set Default Controller using Route

Open the config/route.php file and define the basic application controllers. Go to Router :: scope () and in $builder->connect() change the name of the controller from “Pages” to “Posts”, name the action from “display” to “index” and pass parameters to the select view file to use.
$routes->connect('/', ['controller' => 'Posts', 'action' => 'index', 'index']);
You can always support by sharing on social media or recommending my blog to your friends and colleagues.   
If you have any suggestions / problems about this tutorial, please comment on the  form below.😊


Leave a Reply