Tuesday, July 21, 2020

How to create Model in CakePHP 4?

Model is an important component of MVC design pattern, models are basically responsible for storing data and exchange with other layers in the application, in CakePHP models are fat layer and serve as business and data access layer. In addition to these roles’ models can manipulate the data by several other means, for example, files, web services etc. 

Guys, if you don’t know what is MVC design pattern, visit my article What is the Design Pattern of CakePHP 4

Creating Model 

Let’s begin, open the visual studio code, if you have not installed visual studio code, use the command prompt to create the model in your application. It is good idea if you are serious with development then download any good code editor having PHP IntelliSense support. I recommend visual studio code, it is free community edition, rest is up to your convenience. 

On the command prompt, navigate to your application folder and then in bin folder, in my case it is “c:\xampp\htdocs\myshop\bin”. Type the below command for customers table and see the magic. 


The command has invoked the bake utility and created two important classes in their respective folders. The first model class is created under model\table with name CustomersTable and the other class under the model\entity folder with name Customer, both classes are model classes but different responsibilities. The other two classes are generated as part of testing framework and are not part of the discussion in this article. 

Let’s see what is inside each class and how it works. 

Model CustomersTable Class 

CustomersTable class is extended from Table parent class, it inherits several useful features as part of standard package of ORM framework. Table class encapsulate the basic functionality of CURD operation and maintaining the association between multiple tables. 



At the run time when controller requires the model for data insert, update, delete or retrieval, model knows how to handle the request and issue the query to underlying database. All this is handled through Table class provided by the ORM framework. 

The first method in this class is Initialization, here ORM is initialized by setting the table name in the database “Customers”, its primary key name and its display name. These are the minimum configurations required to deal with the corresponding table in the database. 


The second method is ValidationDefault, this method is responsible for the basic validation of the data fields received for insert or update. 



Model Customer Class 

The Customer class extends the Entity parent class, it stores the single row of the table for data manipulation. In this class we can adjust the accessibility of each field. This class is nothing more than just setting the model fields. 



Today we have seen how to create the Model, which is responsible to manipulate data between business and data access layer, model is responsible for data validation. In next article we will see how different views work with models and controllers to visually present the data on customer browser. 

Like and share my article, subscribe for latest articles in future.

Monday, July 20, 2020

How to create controller in CakePHP 4?

Hi guys, in our last article we have seen how to setup database in MySQL. It is the first step to start application in CakePHP, or Database First approach. If you have not seen the article visit the link How to setup Database for CakePHP 4.x Application? Today, we will see, how to create our first controller in application. 

Before starting the coding, I will recommend to download any code editor which support the PHP development, my recommendations is to download Visual Studio Code, it is free community edition and has good support for plugins. After download install the PHP IntelliSense Extension. 

Once you are ready, open the command prompt and create new application, in my case, I have created new application “MyShop” in htdocs folder. If you don’t know how to create CakePHP 4.x application visit the link How to create your First CakePHP 4.0 Application

After creating the application, navigate in to root folder of your application and open the Visual Studio Code. Open the terminal window and move into the bin folder of your application. At the command prompt in the terminal window, type the command as shown below. 


In the command we have invoked the cake bake utility to bake our customer controller, where customers is the table name in my database. Once the command has completed its task you will see that it has created two files first under src\controller\ folder, which is “CustomersController” and the other under test\testcase\controlle\ folder is “CustomersControllerTest”, the first one is your main controller class, and second one is its test case class. We will not discuss the test case class here and leave the topic for other article. 

What is created inside the controller class? 

Let’s open the CustomersController Class in code editor. You will notice that this file contains the CutomersController class which extends the AppController class. AppController is the parent class and all the entity controllers inherits from this class. 

Under this class you will see five methods are automatically created to handle the CURD (Create, Update, Retrieve and Delete) operations. Index and View methods both performs the data retrieval operation but the first one dose pagination of all the available data in the table automatically, View method retrieves one record from the table at a time based on the primary key of table. Other three methods add, edit and delete obvious from their name are used for insert, update and delete. 

At this stage we have fully functional controller to handle CURD operation request. 

Now examine each method one by one. 

Index Method 

In index method on line #20 paginate controller retrieves the customer databased on default pagination settings, pagination settings can be changed by altering the paginate controller properties. After that on line #22 customer data is converted in to array and passed to the corresponding view associated with this view method. In later articles we will examine the views of each methods in this controller. This is the simple job of this method retrieve data from model and pass to view. 



View Method 

In this method on line #34 controller retrieves the single record based on the incoming primary key information and on line #38 it is converted to array and again set to its corresponding view. 



Add Method 
Add method is little interesting, considering the security mechanism this method checks that the incoming data is sent through the POST method of HTTP protocol or not, if it is valid data through POST method of HTTP protocol, then it tries to save the data on line #51, if all is well data will be saved and user will be redirected to index page otherwise operation failed message will be sent back to user. 


EDIT Method 

Edit method works in the similar way as Add method but it accepts the data through PATCH, POST, and PUT methods of HTTP protocol. It tries to save the data on line #75 if successful it redirects the user to index page with success message, otherwise sends the operation fail indication to user. 



Delete Method 

Delete method accepts the data via POST or DELETE methods of HTTP protocol, but it only accepts the primary key of the table to delete the record. It deletes one record at a time. 


In the later articles we will see, how the relevant Views of each method works and interact with the user. 

So guys today we have created our first controller and examined the code of controller. We learned the different method are available in the controller and their functions. This is fully functional controller. We can modify the details of each method depending upon the requirement of the application. But this bare bone structure is fully operational. 

Stay tuned with us, share, like, subscribe the article and my blog.

Saturday, July 18, 2020

How to setup Database for CakePHP 4 Application?

Hi guys, In the last article we have seen the strategy for CakePHP application development, till now in the series of articles we have seen the different aspects of CakePHP application development, Its installation, basic configuration, setting up database server, MVC design pattern, the strength of ORM and RDF (Rapid Development Framework) Bake console Utility, which is a plug-in of CakePHP. 

If you have not seen previous articles visit the home page of Deep Space

As discussed in the last article the best approach of starting the application in CakePHP is Database First. So we need database, before we start developing application. For the purpose of learning, I have downloaded a classic database from MySQL Tutorial. You can download the sample database form this website. The downloaded file will be in a zip file format. 

Now open the phpMyAdmin application in your web browser using (localhost/phpmyadmin) address. Once the phpMyAdmin interface opened, click on the import button and chose your downloaded database zip file. This zip file contains the MySQL script. After executing the script you can verify by clicking on the database name in the left pan. 

Important: If you want to change the name of your database, open the script file and change the database name in script file. In my case I have changed it to “myshop”. 



After clicking on the table name under the database, you can see the table has seeded data as well for application development. 

The last step is to create a database user, who will connect the database from the application and grant the privileges to user for secure database access. If you have no idea about this check my article How to Interact with MySQL?

OK, we have setup our sample database for application development today, in the next article we will move to application side and see how to connect to this database and more. Stay tuned with us and like, share, follow and subscribe whatever option you have to be updated with our new articles.


Thursday, July 16, 2020

What is CakePHP 4 Development Strategy?

Hi guys, in the last article we have discussed the design pattern of CakePHP 4.0, today we will discuss the development strategy. When we talk about strategy, first question comes in the mind from where we should start. So the answer is in CakePHP we should start from the root. The best practice is to build your database first and then application, in CakePHP 4.0 you will get great advantage with database first approach. We will see below what other features are in CakePHP 4.0 to make our development fast.

If you have not seen the early articles related with CakePHP4.0 visit the main page here.

CakePHP is based on PHP scripting language, means you have a lot of coding power, but the main advantage of CakePHP is, the MVC design pattern and it has ORM (Object Relational Mapping) as a default feature.

CakePHP ORM (Object Relational Mapping)

To make effective use of ORM, the most important thing is to follow the CakePHP conventions. For more detail on conventions check the CakePHP Conventions.

For example if I have to retrieve all the records from my Student Table, I will write the simple code as below.


Use Cake\ORM\TableRegistry

$students = TableRegistry::getTableLocator()->get(‘Students’);

$query = $students->find();

foreach ($query as $row) {           

$row->firstname;

}

Here you have seen that I have not wrote any SQL query, and I have retrieved the data rows form the student table. In fact SQL query is issued but all the job is handled by the ORM behind the scene.  

Bake Console is another amazing plugin available in CakePHP 4.0 

Bake Console

It is a rapid development console based tool. It helps you to build fully functional application within minutes following the previously explained two concepts MVC and ORM. Before you use this tool you have to install it with the help of Composer from the command prompt. You have to type the following command in the root of your application.

Bake Console

Once you have installed CakePHP Bake, navigate to your application BIN folder and type the below command to check the available options with Bake Utility.

Bake Console

Using the Bake utility you can create Model, Controllers, View and many more components just with a single console command. If proper conventions are followed then this auto generated code is not an empty template but it is a fully functional code. Either you have to tweak as little or none.

Today we learned about some more helpful things which will help us to develop the application faster. In the next article we will use the Bake Utility and build a simple running application.

Stay tuned with us and subscribe our blog.


Wednesday, July 15, 2020

What is the Design Pattern of CakePHP 4?

CakePHP 4.0 follows the MVC (Model-View-Controller) design pattern. MVC consist on three main components. Model, View and Controller

MVC

Model

Any application which is dynamic in nature depend on data, model is the container of data.  For example, Student is a model, it contains its related data like First Name, Last Name, Roll Number and Grade. In programming languages data is encapsulated in the objects of as class. Model has a central role in MVC design pattern, whole application revolves around the model. It is used to temporary store data, validate data, and facilitate to permanently store the data in databases. In CakePHP 4.0 model is fat layer as compare to two other components.

View

View is a perspective of viewing the data graphically, it retrieves the data from model and represents on the page in HTML. For example Student may have different perspectives like its Personal Information, Its Educational Record, or its extra curriculum achievements. Each of these groups of information is handled through models and represented on screen either in tabular format or in any other graphical format like bar charts pie charts etc.

Controller

Controller is the middle layer between model and views, main objective of controller is to receive the request, arrange the data through models and handover to views for display and vice versa. In CakePHP controllers are slim layer.

Today we have seen the design pattern of CakePHP 4.0. It is important to understand the concept of MVC, because whole development of application is dependent of these three types of components. In the next article we will see the whole concept in action through the code.


Tuesday, July 14, 2020

How to Interact with MySQL?



Welcome, in our last article we have seen that CakePHP 4.0 application is up and running, but it was not able to connect to the database. The reason behind this is that we have not yet created any database. To make connection with database it is good idea to learn some basics about MySQL before proceeding further in CakePHP 4.0 application development. 

phpMyAdmin

phpMyAdmin is PHP based MySQL administration tool, it is free and by default installed with XAMPP control panel. There are many free and paid tools for MySQL administration but for the learning and development purpose phpMyAdmin is more than enough. 

Let’s start phpMyAdmin, go to your windows start menu and start the XAMPP control panel. Start the Apache service and MySQL service. When both services are up and running, jump to web browser and type “localhost/phpMyAdmin”. It will start the application and you will see the page like below.

phpMyAdmin

Create New User in MYSQL

Click on the “User Accounts” menu on the menu bar as shown in the image.

phpMyAdmin

Click on “Add User Account”. 

phpMyAdmin


On the Login information form enter the login information in “User Name” and in “Password” text boxes, type the same password again in the “Re-Type” text box.

phpMyAdmin

Click on the “Go” button given on the extreme right bottom of the page. If not visible scroll down the page.

At this stage a new database user is created. Till now we have not assigned any privileges to this user. We will do this later in the article.

Create New Database

Click on the “Databases” menu.
Enter the database name in the text box, as I entered “MySchool”, you can enter name of your database.

phpMyAdmin

Next click on the “Create” button. It will create the new database and will lead you to new page for New Table creation.

Create a New Table in Database

1) Enter the table name “Students” in the name field. You can enter your table name. in the number of column text box enter the count of your table columns in my case I have entered 3.

phpMyAdmin

Click on the “Go” button, on right side of the page.

On the next page fill the data as shown in the below image.

phpMyAdmin


Click on the “Save” button in the right bottom of form. it will create the new table.

Assign Privileges to User

Go to “User Accounts” page.

Select the Used “DBAdmin” by checking the checkbox in my case.

phpMyAdmin

Click on the “Edit Privileges” link. 

Click on “Databases” tab. Select the “MySchool” database and click on “Go” button 

phpMyAdmin


Now the database is selected for privileges. Click on “Go” button.

At this stage we have created a new user, created a new database, created a new table and assigned the privileges to the newly created user for the newly created database.

Stay tuned with us, in the next article we will move back to CakePHP and connect our application to this database.

Monday, July 13, 2020

How to create First CakePHP 4 Application?


Welcome, today we are ready to create our first CakePHP 4.0 application. Before we create CakePHP 4.0 project we have to do minor modification in the "Php.ini" file. 

Start your XAMPP control panel and click on “Config” button in the Apache service row and select the Php.ini file. It will open the configuration file in the text editor. Now locate the extension intl and un-comment by removing the semicolon from the beginning.



It’s time to create the first CakePHP 4.0 application. Open the command prompt and navigate to your web root folder, in my case it is “C:\xampp\htdocs”. At the command prompt type command as below. 

Composer create-project --refer-dist cakephp/app:4.0 cakephpapp1 


This command will download the CakePHP 4.0 application skeleton and all its required default dependencies initially required to build the application. This process will take some time to download all dependencies. 

This command will create the folder in the htdocs folder with your provided application name. You will see the folder structure as shown in the below in the image. 



Good so we have created our application. Lets verify the newly created CakePHP 4.0 application. Open the command prompt again and navigate to your application folder, type the below command. 

Bin\cake server –p 8765 

This command will start the built-in application test server on port 8765. Open your web browser and type the below address in address bar. 

Localhost:8765 

You will see the CakePHP 4.0 welcome screen, its mean you application is created successfully. 



On the welcome screen you will notice that the application has failed the database connection. In the next post we will discover how to configure database to our application. 



Stay tuned with us, we will learn more and grow more with CakePHP 4.0.

Saturday, July 11, 2020

How to verify the CakePHP 4 development environment?


How to verify the CakePHP 4.0 development environment is it ready to go?

Hi guys, those who have not gone through my last posts, where I have explained step by step how to set up the CakePHP development environment, may check this link Home.

In this post we will proceed further to verify what we have done earlier. You can proceed step by step and confirm that everything is working fine.

Check Our Web Server Apache is working fine?

Open your XAMPP control panel form start menu, once it is started click on the start button opposite to service labelled “Apache”. It will take few seconds to start, once it is Green it means it is running in the background. In case you see the below message in the message window. Follow my post How to install and configure CakePHP 4.0?

Problem detected!
Port 443 in use by ""C:\Program Files (x86)\VMware\VMware Workstation\vmware-hostd.exe" -u "C:\ProgramData\VMware\hostd\config.xml"" with PID 11356!
Apache WILL NOT start without the configured ports free!
You need to uninstall/disable/reconfigure the blocking application
or reconfigure Apache and the Control Panel to listen on a different port

Once you are good to go, open your web browser and type “localhost” in the address bar. It will open the welcome screen of XAMPP dashboard.

You can check the information about installed PHP version by clicking the PHPInfo link on the welcome screen.

Further you can verify your PHP version by typing “PHP -v” on command prompt.


Write your First Hello World script

Guys, if you check the PHPInfo page on XAMPP dashboard, under the Apache Environment section, you will notice that there is one environment variable defined “DOCUMENT_ROOT” its value is “C:/xampp/htdocs” in my case, this is the root folder. All the PHP applications are stored under this root folder. If you want to change this location you can change it in the “httpd.conf” file.

Let’s create a folder under this root, name it “HelloWorld”, create a text file, with the help of any text editor and name it “index.php”. Don’t forget its extension. Copy the below code in the file and save it.

<?php
    echo "Hello World! </br>";
    echo "My First PHP script";

Now move to web browser and type in the address bar “localhost/helloworld” you will see the below result.


So you have successfully executed the your first PHP script.

In the next post we will discover it in more detail, stay with us and subscribe the blog.

How to install CakePHP 4?

CakePHP

How to install and configure CakePHP?

Hello again, those who have not red the first part of this post can visit What is CakePHP?

In the last post we have seen step by step how to install the prerequisite for the environment required for the CakePHP application development. In this part and in up coming post we will configure the environment and write a simple code to prove that the workplace is ready for the application development.

Starting Up Apache Server 

Let’s guys move further, till now we have successfully installed the XAMPP, now double click the XAMPP icon on desktop or select from the start menu. 


Once the XAMPP control panel has started you will notice that it has five service that can be started and configured through this control panel. For the application development two services Apache and MySql are important. Apache is HTTP server and MySQL is database server which will serve as a data store for our application. FileZila is FTP server, Mercury is Mailing Server and the last Tomcat is another open source web server. You don’t need Tomcat when you are using Apache.

XAMPP

Some time when you start Apache it gives error and dose not start, because the predefined ports 80 and 433 conflict with the existing installed application or running services. In this case, you can change these ports easily by modifying the configuration files. You can click on config button and open the “Apache httpd.conf” file. It will open it in the notepad change the port 80 on two locations as below to 8080.

Listen 80
ServerName localhost:80

Similarly you can open the “Apache httpd-ssl.conf” file and change the port 443 to 4433 on the below mentioned locations in the file. Once you have done these modification start the Apache service again it will start and show green which means it is started and running successfully.

Listen 4433
<VirtualHost _default_:4433>
ServerName www.example.com:4433

XAMPP

Installing Composer

Now a day’s all big frameworks and platforms are composed of several useful packages, CakePHP is a rich framework and depends on several packages. CakePHP requires composer which is package manager. We need this package manager to install the CakePHP. You can download the composer latest version form the github. Download

Once the installer setup is downloaded just double click and run the installer. Do not change any setting on the wizard just click next, next install and finish. For your reference images are self-explanatory as below.

Composer Setup

Composer Setup

Composer Setup

Composer Setup

Composer Setup

Composer Setup

Up till now we have installed all the prerequisites and done the configuration need for the application development.

Stay with us in next post we will start the CakePHP. We will create a project and will discover how much CakePHP is sweet.

Friday, July 10, 2020

What is CakePHP 4?


CakePHP



What is CakePHP? 

CakePHP is web application development framework based on PHP (Hypertext Processor). It is an open source scripting language and widely supported by the developers communities. It follows the MVC (Model, View and Controller) development pattern. 

What is the latest version available? 

At the time of this blog the latest version 7.4.8 of PHP released on 9th July 2020, for reference visit the link. CakePHP latest version 4.0 is available, for more information you can visit the link

What’s new in CakePHP 4.0? 

Most important thing in this new release the developers has revamped the application skeleton with more advance APIs which accelerates the development of application. New CakePHP requires minimum PHP version 7.2.

What is required for getting ready with CakePHP? 

To get starting developing application with CakePHP, there are few basic requirements that need to be fulfil.
  1. You need HTTP web server most recommended is Apache HTTP Server. It is an open source project started in April 1996. The latest version 2.4.43 of Apache HTTP Server released on 1st April, 2020. It is available for all modern OS, Windows, Linux, Mac etc.
  2. Minimum PHP version 7.2 but recommended is 7.4 latest.
  3. Minimum PHP extensions installed mbstring, intl, simplexxml and PDO.
The best method to install the PHP and Apache server is to download the XAMPP (Apache + MariaDB+ PHP+Perl) installer and it makes your life easy. The XAMPP installer is available on the following link

How to Install XAMPP? 

Go to the XAMPP website and download the latest version for your desired OS platform. 

For this blog we will download the windows based installation package. 

Steps you need to follow the installation.

Once it is downloaded on your drive, go to the location and double click the installer executable file. If you see the below screen, ignore the message and click on yes to continue with installation.


Then you will see another warning like below, It is recommended to install it to another location instead of C:\Program Files.




After clicking on OK on the warning dialog, welcome scree of installation wizard will appear. Click on next.


On select component page you can unselect the optional component but it is recommended to install all the components, you will need them at later stage. Click on next.


On next page select the installation location, you can select any location other than the C:\ Program Files, it is not recommended due to security restriction of windows. Click on next.


On next page select your language and click on next.



Click next and Click next, it will start installation. Installation process will take some time based on the speed of your computer.


After installation it will ask you to allow the access to Apache server through firewall. Allow access either on you private network or public network as per your need and finish the installation.



Once you have installed XAMPP with all its option, you have setup your basic development environment. Well done.

The mission is not ended here, to continue please subscribe the mailing group so you can hear from us when new blogs are published.

In the next blog we will continue the configuration of XAMPP and installation, configuration of CakePHP. Stay with us.