CakePHP on cloud

1-click AWS Deployment   1-click Azure Deployment 1-click Google Deployment

Overview

CakePHP is an open-source framework that helps make the development and maintenance of PHP apps much easier. It is based on the concept of MVC architecture. It helps you to separate your business logic from data and presentation layers.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.

Application flow of the CakePHP are given below:

cakephp-application-flow

Download CakePHP

At first you need to download the stable release of CakePHP from Github – CakePHP Releases

Basic Configuration

  • Step1: Extract zip file and change folder name with your desire project name. For example cakephp/.
  • Step2: Move the cakephp/ folder to the localhost server. Your directory setup looks like the following.
    • /cakephp
      • /app
      • /lib
      • /plugins
      • /vendors
      • .htaccess
      • index.php
      • README
  • Step3: Create database at the phpMyAdmin. For example cakephp_db.
  • Step4: Open the app/Config/core.php file and make the following changes.
    •  Change the value of Security.salt at Line no.225.
      • Before changes:
        Configure::write('Security.salt', 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi');
      • After changes:
        Configure::write('Security.salt', 'codexworld');
    •  Change the value of Security.cipherSeed at Line no.230.
      • Before changes:
        Configure::write('Security.cipherSeed', '76859309657453542496749683645');
      • After changes:
        Configure::write('Security.cipherSeed', '123456');
  • Step5: Rename database.php.default file to database.php at the app/Config/ directory.
  • Step6: Open the “app/Config/database.php” file and make the following changes.
    •  Go to the line no.67 and replace the values of host, login, password, database_name with your database host, database username, database password and database name.
      • Before changes:
        public $default = array(
            'datasource' => 'Database/Mysql',
            'persistent' => false,
            'host' => 'localhost',
            'login' => 'user',
            'password' => 'password',
            'database' => 'database_name',
            'prefix' => '',
            //'encoding' => 'utf8',
        
        );
      • After changes:
        public $default = array(
            'datasource' => 'Database/Mysql',
            'persistent' => false,
            'host' => 'localhost',
            'login' => 'root',
            'password' => '',
            'database' => 'cakephp_db',
            'prefix' => '',
            //'encoding' => 'utf8',
        );
  • Step7: Run the project URL(http://localhost/cakephp/) at the browser.
    screencapture-cakephp-configuration

CakePHP Naming Conventions

  • Controller Conventions – Controller class names are plural, CamelCased and end in Controller.(PostsControllerLatestPostsController)
  • Model Conventions – Model class names are singular and CamelCased.(PostLatestPost)
  • Database Conventions – Table names corresponding to CakePHP models are plural and underscored. (postslatest_posts)
  • View Conventions – View template files are named after the controller functions they displayed, in an underscored form. The postDetails() function of PostController class will look for a view template in app/View/Post/post_details.ctp. The basic pattern is app/View/Controller/underscored_function_name.ctp

Sample Project

In this sample project we will create a products table at the cakephp_db database. And we will insert some data manually at this table. We will fetch and display products in our sample CakePHP project.

Table Creation & Data Insert: Following SQL is used for products table creation.

CREATE TABLE `products` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `description` text COLLATE utf8_unicode_ci NOT NULL,
 `price` float(10,2) NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Once table creation is completed, insert some demo product data into this table.

Controller: Create a products controller with ProductsController class into the app/Controller/ directory. Controller file and class name should be ProductsController.

<?php
class ProductsController extends AppController {
    public function index() {
        //fetch products resultset from databse
        $products = $this->Product->find('all',array('fields'=>array('Product.id','Product.title','Product.description','Product.price','Product.created','Product.status'),'conditions'=>array('Product.status'=>1)));

        //set products data and pass to the view 
        $this->set('products',$products);
    }
}

View: Create view for display products in app/View/ directory. The controller class name is ProductsController and method is index. For creating the index view, we need to Products/ directory and a index.ctp file. So, the complete path of the view file (index.ctp) would be app/View/Products/index.ctp.

<ul>
<?php foreach($products as $row): ?>
    <li>
        <h1><?php echo $row['Product']['title']; ?></h1>
        <h6>Price: <?php echo $row['Product']['price']; ?></h6>
        <p><?php echo $row['Product']['description']; ?></p>
    </li>
<?php endforeach; ?>
</ul>

Model: Model creation is not required until you need validation or associations.

Routes: Open the app/Config/routes.php file and set the default controller and action. Go to the line no.27 and change controller name from “pages” to “products” and action name from “display” to “index”. If you want to load the different view for this action, you need to pass the view file name after the action element.

Router::connect('/', array('controller' => 'products', 'action' => 'index'));

Testing: Run the base URL at the browser, products list would displayed.

screencapture-cakephp-display-data

 

Benefits of using CakePHP Framework?

  1. Rapid Development: CakePHP is known for its “convention over configuration” approach, which allows developers to quickly build web applications. It provides a set of pre-built functionalities and follows the MVC (Model-View-Controller) architectural pattern, making it easy to create and organize code.
  2. Code Reusability: CakePHP promotes code reusability through its modular design and extensive library of components, behaviors, and plugins. Developers can leverage these ready-made components to speed up development and reduce the amount of code they need to write from scratch.
  3. Security: CakePHP includes built-in security features to help developers protect their web applications from common vulnerabilities, such as SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF). It provides mechanisms for input validation, form tampering protection, and data sanitization, making it easier to build secure applications.
  4. Database Abstraction: CakePHP provides a powerful Object-Relational Mapping (ORM) layer, called CakePHP ORM. It simplifies database interactions by abstracting the underlying SQL queries, allowing developers to work with databases using a more intuitive and object-oriented approach. This helps reduce the complexity of data retrieval, manipulation, and persistence.
  5. Active Community and Documentation: CakePHP has an active and supportive community of developers who contribute to its growth and provide assistance through forums, chat channels, and open-source projects. The framework also offers comprehensive documentation, tutorials, and guides, making it easier for developers to get started and find answers to their questions.

Why we use CakePHP

uses of CakePHP

CakePHP has several features that make it highly recommended as a framework for quick and risk-free implementation of applications.

  • User-friendly Tool: It is helpful to create a complex web application directly. Furthermore, we can easily customize the web application as per our needs in CakePHP applications. It allows us to create coding in the template editor quickly.
  • Robust Performance: It also provides a built-in data validation process in CakePHP for validating the web application. Furthermore, it makes the complex structure simpler for the development of the website by the use of advanced tools that are supporting your developing site across the world.
  • Compatibility with PHP4 and the above version: CakePHP’s application is supported with PHP4 and a higher version of PHP for the smoothly running web application.
  • CRUD development: A CakePHP provides a beneficial thing for the development of an application is CRUD. A single line of code in crud can generate the database application for performing various tasks like create update and delete operation. Furthermore, it can be customized based on a specific requirement of the business application.
  • Innovative Ability: All the applications of CakePHP support unit testing and provides some essential details for the functionality of your application also it supports multi-talent resource for the enhancement of the knowledge.
  • Model View Controller (MVC) Architecture: It is based on the MVC pattern for handling the query to the database. If the user wants to alter the information that is saved on the database, then CakePHP allows to perform various task like insert, delete and update the details which you have filled in your database.
  • Easily Extendable: CakePHP allows you to reuse their codes by writing at one time and reuse their component or method more than a single page. Furthermore, CakePHP also provides some functionality that can be used in your application like helper, plugins, and behaviors for directly calling in your application.
  • It provides a fast and easily changeable template by use of PHP syntax with helpers.
  • Security, Session, and Request Handling Components: In CakePHP, there is a built-in function to protect your application is security and authentication. It allows you to protect your web application while performing CRUD operations in your database. Besides, this it also creates a session for the web site user, if the user has not been interacting with the site for the last few minutes, it automatically closes that page and send your response on the front page of the applications. Furthermore, it handles the request or loading the component in your application by calling the element in your controller.

CakePHP in detail…..

  • CakePHP was created by Michal Tatarynowicz in early 2005 as a minimalistic framework for his own web applications.
  • It was inspired by Ruby on Rails and aimed to bring Rails’ benefits to the PHP community.
  • CakePHP was released as an open-source project under the MIT license.
  • Version 0.1, the first public release, came out in April 2005.
  • CakePHP gained popularity quickly due to its simplicity, conventions, and built-in features.
  • Version 1.0, released in 2006, marked a significant milestone for CakePHP with improved functionality and support.
  • Version 1.1 introduced enhanced model associations and improved routing.
  • Version 1.2 added built-in support for database migrations.
  • In 2011, CakePHP 2.0 was released, bringing modern PHP practices, improved performance, and better security features.
  • CakePHP 3.0, released in 2014, focused on performance, flexibility, and usability, embracing PHP 5.4 and above.
  • CakePHP 4.0, released in 2019, further refined the framework with newer PHP versions and a more streamlined API.
  • CakePHP continues to release updates, improving performance, security, and developer experience.
  • It remains popular for its ease of use, convention-over-configuration approach, and extensive feature set.

CakePHP Folder Structure details

The folder structure of a typical CakePHP application follows a set convention that organizes the files and directories in a way that promotes code organization and separation of concerns. Here is an overview of the standard folder structure in CakePHP:

  • app/: This is the main folder of your CakePHP application.
    • bin/: Contains executable scripts related to the CakePHP project.
    • config/: Contains various configuration files for the application.
      • app.php: Configuration file for general application settings.
      • bootstrap.php: File responsible for bootstrapping the CakePHP framework.
      • routes.php: File for defining application routes.
      • : Other configuration files.
    • src/: The source code of your application.
      • Controller/: Contains the application’s controllers.
      • Model/: Contains the application’s models (representing the data layer).
      • Template/: Contains the application’s templates (views).
      • Form/: Contains form classes used for form handling and validation.
      • View/: Contains view classes used for rendering views.
      • : Additional directories and files for custom code.
    • plugins/: Directory for CakePHP plugins used in the application.
    • logs/: Directory for log files generated by the application.
    • tmp/: Directory for temporary files, such as cached data and session files.
    • vendor/: Directory for third-party libraries and dependencies installed via Composer.
    • webroot/: The web-accessible root of the application.
      • css/: Directory for CSS files.
      • img/: Directory for image files.
      • js/: Directory for JavaScript files.
      • index.php: The entry point of the application.

Additionally, there are some other important files and directories outside the app/ directory:

  • bin/: Contains executable scripts related to CakePHP’s command-line interface (CLI).
  • config/: Contains global configuration files for the CakePHP installation.
  • plugins/: Contains globally installed CakePHP plugins.
  • tests/: Directory for testing-related files, including test cases and fixtures.
  • vendor/: Directory for globally installed Composer dependencies.

The folder structure may vary depending on the specific version of CakePHP and any customizations made to the default setup. However, the outlined structure provides a foundation for organizing the various components of a CakePHP application.

CakePHP Configuration

CakePHP Configuration

When we install CakePHP software in our system, then it provides a predefined config folder, and we can modify it according to our needs in the application. CakePHP provides some configuration.

General Configuration

Here we have listed various elements and their descriptions in CakePHP configuration. In this configuration, we will learn about the component of CakePHP, how they affect your application.

Debug

It Changes the CakePHP-debugging output

false = Production mode (when you define debug is false then it will not show any error or warning message)

true = by defining true, it will show an error and warning too.

App.namespace

The namespace element is usually used to find the app class that is defined in the config folder.

App.baseUrl

If you want avoid the use of Apache’s mod_rewrite in your Cake PHP application, then you can uncomment it. Don’t forget to delete your .htaccess files as well.

App.base

The base directory app is in the config file and can auto-detect if the base directory is not present. And if you have not provided the correct base, it means that your string starts with a / and does not end with /.

App.encoding

The encoding/format is used to represent your data in the application that generates set characters in designing and encode entities. Besides, it will match all encoding values ​​that are specified in your database.

App/webroot is the webroot directory.

App/wwwRoot – shows the file path to the Webroot.

App.fullBaseUrl

It provides the full url path to your application’s root. By default, $_SERVER is used to generate an absolute url in CakePHP. Although you can use it manually to optimize the performance.

App.imageBaseUrl

You can define your image path on the web page under Webroot.

App.cssBaseUrl

You can define your CSS file path on the web path under the Webroot folder.

App.jsBaseUrl

In the folder of Webroot, you can define your js file to the web path.

App.paths

It configured a path that is based on non-class resources such as plugins, location subseries, templates that provide definition paths for plugins, view templates, and locale files.

Security.salt

It uses a random string for hashing. For this purpose, it uses the HMAC salt to provide security to your database value.

Asset.timestamp

It contains a digital record of the last modified file using the asset. timestamp. Also, it records the particular file at the end of the Asset Files URL (CSS, JAVASCRIPT, IMAGE), when appropriate coding values ​​are used.

(bool) false – it will not perform any task.

(bool) true – It appends the timestamp interval when debug is true.

(string) ‘force’ – It always adds the timestamp.

Database Configuration

All the connections related to the database can be configured in config / app.php. And this file can be called in Cake \ Datasource \ ConnectionManager to establish the database connection configuration in your application.

When you configure all the database settings in your config/app.php file, then it will show the given below image in your localhost server.

 Cake PHP Successful

And if you are using mysql for database connection, then you have to define the given below connection in your application.

Cake- PHP naming conventions

CakePHP follows a set of naming conventions that promote consistency and standardization within the framework. Here are the key naming conventions used in CakePHP:

  1. Class and File Names:
    • Class names should be in CamelCase.
    • Controller classes should be suffixed with “Controller” (e.g., PostsController).
    • Model classes should be suffixed with “Table” (e.g., UsersTable).
    • View classes should be suffixed with “View” (e.g., IndexView).
    • Helper classes should be suffixed with “Helper” (e.g., FormHelper).
  2. File and Folder Structure:
    • Class files should be named after their respective classes, with the filename matching the class name (e.g., PostsController.php).
    • Controllers should be placed in the Controller directory.
    • Models should be placed in the Model/Table directory.
    • Views should be placed in the Template directory, under the corresponding controller’s directory.
  3. Database Table Names:
    • Database table names should be in lowercase and pluralized.
    • Table names should use underscores to separate words (e.g., users, blog_posts).
  4. Controller Actions and URLs:
    • Controller actions (methods) should be in lowerCamelCase (e.g., index, editPost).
    • URLs follow a lowercase, hyphenated format for controller and action names (e.g., /users/edit-post).
  5. View Templates:
    • View templates should be named after the corresponding controller action, using lowercase, hyphenated format (e.g., index.ctp, edit-post.ctp).
  6. Variable Names:
    • Variable names should be in lowerCamelCase (e.g., $userName, $postTitle).

Following these naming conventions in CakePHP helps maintain a consistent codebase and improves code readability. Additionally, adhering to these conventions allows the framework to automatically associate components, models, views, and actions based on the naming patterns, making development more efficient.

Databases Configuration

In CakePHP, the configuration for connecting to databases is typically done in the config/app.php file. This file contains an array named 'Datasources' where you can define one or more database connections. Here’s an example of how the database configuration looks in CakePHP:

 
In this example, the 'default' key represents the default database connection. You can define additional connections by adding more keys to the 'Datasources' array.

Here’s an explanation of the key configuration options:

  • 'className': Specifies the class to use for the database connection. In this case, 'Cake\Database\Connection' is used.
  • 'driver': Specifies the database driver to use. For example, 'Cake\Database\Driver\Mysql' for MySQL.
  • 'persistent': Set it to true if you want to use a persistent database connection.
  • 'host': Specifies the database host.
  • 'username' and 'password': The credentials for accessing the database.
  • 'database': The name of the database to connect to.
  • 'encoding': Specifies the character encoding for the database connection.
  • 'timezone': Specifies the timezone to use for the database connection.
  • 'cacheMetadata': Set it to true to enable metadata caching for improved performance. It’s recommended to keep this option enabled in production.

You can add additional configuration options as needed, depending on the database and driver you are using. Once the configuration is set, CakePHP will use this information to establish a connection to the database when needed.

MVC in CakePHP

CakePHP follows the Model-View-Controller (MVC) architectural pattern, which provides a structured way to develop web applications. Here’s how MVC works in CakePHP:

  1. Model (M):
    • The Model represents the data and business logic of the application.
    • In CakePHP, Models are responsible for handling database interactions, data validation, and business rules.
    • Models retrieve, store, and manipulate data from the database.
    • Models are typically located in the src/Model/Table directory and extend the Cake\ORM\Table class.
  2. View (V):
    • The View is responsible for presenting data to the user.
    • In CakePHP, Views are used to generate the HTML output that is sent to the browser.
    • Views are typically located in the src/Template directory and contain PHP templates (.ctp files) with HTML and embedded PHP code.
    • Views retrieve data from the Controller and display it to the user.
  3. Controller (C):
    • The Controller acts as an intermediary between the Model and the View.
    • In CakePHP, Controllers handle user requests, process data, and prepare the response.
    • Controllers receive user input, interact with the Model to retrieve or update data, and pass the data to the View for rendering.
    • Controllers contain action methods that correspond to different user actions.
    • Controllers are typically located in the src/Controller directory and extend the Cake\Controller\Controller class.

The flow of data and control in CakePHP’s MVC pattern is as follows:

  1. The user makes a request by accessing a URL.
  2. The request is routed to the appropriate Controller and action based on the URL.
  3. The Controller’s action method is executed, which may involve retrieving data from the Model, processing it, and preparing a response.
  4. The Controller passes the necessary data to the View for rendering.
  5. The View receives the data from the Controller and generates the HTML output.
  6. The generated HTML output is sent back as a response to the user’s request.

CakePHP’s MVC architecture helps separate concerns and promotes a clear separation of responsibilities between the Model, View, and Controller components. This separation enhances code organization, maintainability, and reusability, making it easier to develop and maintain complex web applications.

CakePHP is an open-source MVC framework. It makes developing, deploying and maintaining applications is easy. CakePHP has number of libraries to reduce the overload of most common tasks. Following are the advantages of using CakePHP.

  • Open Source
  • MVC Framework
  • Templating Engine
  • Caching Operations
  • Search Engine Friendly URLs
  • Easy CRUD (Create, Read, Update, Delete) Database Interactions.
  • Libraries and Helpers
  • Built in Validation
  • Localization
  • Email, Cookie, Security, Session, and Request Handling Components
  • View Helpers for AJAX, JavaScript, HTML Forms and More

CakePHP Request Cycle

The following illustration describes how a Request Lifecycle works −

CakePHP Request Cycle

A typical CakePHP request cycle starts with a user requesting a page or resource in your application. At a high level, each request goes through the following steps −

  • The webserver rewrite rules direct the request to webroot/index.php.
  • Your application’s autoloader and bootstrap files are executed.
  • Any dispatch filters that are configured can handle the request, and optionally generate a response.
  • The dispatcher selects the appropriate controller & action based on routing rules.
  • The controller’s action is called and the controller interacts with the required Models and Components.
  • The controller delegates response creation to the View to generate the output resulting from the model data.
  • The view uses Helpers and Cells to generate the response body and headers.
  • The response is sent back to the client.

Structure of CakePHP

Model-view-controller

It is a pattern in software design that allows you to differentiate the code logically, make it more reusable, maintainable, and generally better.

Model

In Cake Terms, the model represents a specific database table/record, and its relationship to other tables and files. The model also has rules to validate your data that implement the inserted or updated operation in your database table. Handles all data processing, validation, and association that related to the data

View

It works as a Presentation layer that displays the information in such a way that can be beneficial for the user. What to end-user sees on the web browser.

Controller

It interacts with the model and view to deliver a response to the user. The controller handles the requested data, ensuring that the correct model is called and the proper response or view is provided.

Structure of CakePHP

You can see the folder structure of CakePHP, described below.

Structure of CakePHP

Folder Name & Description

Bin

The bin folder contains the Cake console executables files.

Config

The config folder contains some configuration files for CakePHP uses. Database connection details, route files, bootstrapping, core configuration files, and more.

Logs

The log folder usually holds some log files of your application based on the log configuration.

Plugins

A CakePHP plugin which is used for providing additional functionality in your application. You can also reuse it in other applications of CakePHP.

Src

The src folder contains the MVC files of your application. In this folder, you will put your CakePHP files for the development of web applications.  Now, take a look at the src files in brief.

  1. The console holds the console command prompt for running your application file.
  2. A Controller that holds the controller’s files and their components too.
  3. The locale contains string files for internationalization.
  4. A model that is used for connecting with the database table, so it holds the application’s tables, entities, and behavior.
  5. The view is a presentational class that placed in cells, helpers, and template files, which can call in the controller file.
  6. A template is also a presentational file that put in element, error pages, layout, and view template files

Tests

The test folder which contains the test cases of your application.

Tmp

Tmp is a folder of CakePHP in which it stores the temporary file, and the actual data depends on the configuration of CakePHP. This folder is used for storing the model data, and sometimes it can store session information.

Vendor

The vendor is a folder of CakePHP in which it holds the dependencies of CakePHP and other applications. So, we can’t edit these files, and if you changed by mistakes, then the composer will overwrite your previous record.

Webroot

The webroot is a folder of CakePHP in which it contains all the public document which you want to fetch in your helper class like jpg, CSS, javascript file.

CakePHP Request Cycle

A CakePHP request cycle begins with a user-requested page in your application program. At each stage of the application, the user-requests are passed one by one.

CakePHP Request Cycle
CakePHP Request Cycle
  1. Suppose a client request for a particular item on the web browser. Then the request carried out by the dispatcher. Example: suppose a user wants to fill his examination fee online. The dispatcher, filter the client request from the number of applications on the server, send their request for a particular web server.
  2. Dispatcher filters or select only the routes that have been requested by the client that can be configured and handle the request.
  3. A large number of routes are determined for the request in the respective controller and take action based on routing rules.
  4. Then the controller’s action is implemented, and the controller interacts with the required model and components. It takes dynamic data from the model that is relevant to the request. Example When you fill the contact_us / feedback page in your web application, the model stores the details in the format of the data source and behavior. We can also identify from which website we have collected the details
  5. The controller can check dependencies from component and database models, send feedback to the view.
  6. CakePHP uses a view helper and element to generate a responsive body.
  7. And finally, the requested page will show to the user web browser.

CakePHP Controller

 

Controller

A Controller, as the name suggests, is a controller that controls the web application by calling the correct action. The controller takes the request from the user through dispatchers like action, which makes sure the right models and views are called. So, it acts as a bridge between models and views.

AppController

The AppController class is the superclass of all controllers, which extends the main Controller class. This class is predefined in src/Controller/AppController.php, and it contains some function that’s shared between all of your controller applications. This class expands CakePHP’s controller class.

Controller Actions

All the method of the controller, which is predefined in the controller class, is known as Actions. It is responsible for handling the request and sending an appropriate response to the browser. It represents output in the form of visuals that can be provided to create a responsive browser for the user. Furthermore, the view file is rendered in the controller by defining the action in controllers.

Syntax:

Or

Here, action_name()  and index () methods are the activities that can be called by the controller in your localhost server.

Here is an example in which we will learn how to create a controller in CakePHP.

Step1. Firstly, we have to go to our localhost server like wamp or xampp of the C directory folder. If in your system have installed a wamp server, then go to www folder and click on the CakePHP folder, which you have created during the installation of CakePHP. If your system has xampp installed, then click on the xampp folder of C directory, where you will see an htdocs folder. In that folder, you will find the name of that folder which you have created during the installation of CakePHP via Composer. In the given below image, you will find the folder name of your project.

Step2. Now click on the CakePHP folder of your project, then it will show you this page.

click on the CakePHP folder of your project

Step3. Now click on the src folder.

click on the src folder

Step4. After clicking at the src folder, you will find the controller, view, model and template folder.

After clicking at the src folder

Step5. Click on the Controller folder in which you have to create a Controller file with the use of controller name as a suffix in Controller class like FirstsController.php and SecondsController.php. Here we have created many controllers in the CakePHP3.8 folder.

Click on the Controller folder

In this example, we have created our controller with the name of FirstController.php.

Now you have to run this file on the local server like wamp or xampp by writing on the URL like localhost/CakePHP3.8/First/fun

  1. Cakephp3.8 is the folder name of your project
  2. You can write your Controller name either in a small letter or capital letter like First/first is the controller name
  3. fun is the action name that you have to call in your Controller after writing the Controller name in your localhost server.

When you run your Controller in the localhost, then it will show an error “Missing Template” because you have not created a view file for this text on the server.

run this file on the local server

NOTE: – If you don’t want to create a template file, then you can run your controller by the use of this syntax “$this->autoRender=false”. You have to define this syntax in your action method of a controller like this.

FirstController.php

method of a controller

Here we have created multiple actions in LastsContoller.php.

And if we want to run a particular method from two or more method, then we have to pass that method on the localhost server by writing simply

localhost/CakePHP3.8/Controllername/method name

Use of initialize method

This method is used to load the component or process in the controller by defining their name. CakePHP provides an initialize() method that called the component at the end of a Controller’s constructor for direct accessing.

 

-CakePHP makes building web applications simpler, faster and require less code.CakePHP is a rapid development framework for PHP which uses commonly known design patterns like Active Record, Association Data Mapping, Front Controller and MVC.

CakePHP is owned by CakePHP (https://cakephp.org/) and they own all related trademarks and IP rights for this software.

Cognosys provides hardened and ready to run images of CakePHP on all public cloud ( AWS marketplace and Azure).
Deploy your CakePHP securely on cloud i.e. AWS marketplace and Azure with Reliable Services offered by Cognosys at one-click with easy written and video tutorials.

Secured CakePHP on Windows 2012 R2

         Secured cakephp on centos

CakePHP on cloud For AWS

CakePHP on cloud For Azure

Our primary goal is to provide a structured framework that enables PHP users at all levels to rapidly develop robust web applications, without any loss to flexibility.

Features

Top 6 Cakephp Features That Enhance Web Development Process

1. User-Friendly Tool:

One reason behind getting widely accepted and used is that, it is extremely user friendly. It helps you to complex websites in simple way. Moreover, with CakePHP, it is easy to customize the website as per the business requirements. It lets you build designs with the help of template editor easily.

2. Robust Performance:

Another good thing about CakePHP is that, it provides flexible data validation process. Moreover, it makes the complex structures simple for your website with the help of the advanced tools, ultimately supporting you to develop the websites in the languages being used across the world.

3. Innovation Ability:

One best thing about CakePHP development is that, it supports unit testing and provides necessary skills to make sure that it offers best functionality and provides multi-talent resources with extensive knowledge.

4. Reasonable Approach:

It helps you to keep your business website ahead of your competitors and links it with your targeted audience; it helps you satisfy your clients and achieve your business goals. In short, it is one of the easiest and the best way to create qualitative applications at the affordable rates.

5. CRUD Scaffolding:

This is one of the best things about CakePHP web development, as the single line of code can generate the website application and it provides three major activities for your app. Well, the word CRUD stands for Create, Read, Update and Delete and most importantly, it can be customizable on the basis of the specific business requirements to cater all the needs necessary to achieve goals.

6. Testing Method:

It is extremely difficult to analyze the important points and fix the errors in your web applications and business websites and you can do it with the testing process which CakePHP enables you when you hire CakePHP developers. It simplifies your work when you develop a huge application with errors. It helps you identify the bugs.

Features and Enhancements in CakePHP 3.5

Scoped and New Middleware

The new middleware added to CakePHP 3.5 makes it easier for PHP developers to apply encrypted cookies and cross-site request forgery (CSRF) tokens. At the same time, the programmers also have option to build specific middleware stack for different parts of the web application. They can even apply middleware conditionally to routes in specific URL scope. CakePHP 3.5 even allows them to build middleware stack without writing URL checking code.

Cache Engine Fallbacks

The enhanced CakePHP features allows CakePHP developers to configure cache engines with a fallback key. The programmers can define custom cache configuration through the fallback key. If the cache engine is not unavailable or misconfigured, the cache engine will automatically fall back on the custom cache configuration defined through the fallback key.

Improved Console Environment

The updated version of CakePHP enables PHP developers to build web application in an improved console environment. The web developers can integrate the application class into the command-line interface (CLI) environment using a new console dispatcher provided by the framework. They can further accelerate console commands testing by taking advantage of integrated testing helpers. At the same time, CakePHP 3.5 suggests valid options to PHP programmers through missing options and subcommands.

Cookie Objects

CakePHP 3.5 comes with two new classes – Cookie and CookieCollection. These new classes enable PHP developers to work with cookies in an object oriented way. At the same time, the developers can access the classes while working with Cake\Http\ServerRequest, Cake\Http\Response, and Cake\Http\Client\Response.

Built-in dotenv Support

The version 3.5 of CakePHP makes the application skeleton support dotenv natively. While using CakePHP 3.5, programmers can take advantage of a robust zero-dependency module like dotenv to work with environment variables more efficiently. Dotenv further makes it easier for PHP developers to configure applications using environment variables, while keeping the configuration and code separated.

New Methods

CakePHP 3.5 also comes with new methods related to console, collection, database, datasource, event, ORM, routing, validation, testsuite, and view. The new methods enable PHP developers to work with various components of CakePHP more efficiently. They can even use the new methods to accomplish varying web development tasks without writing additional code.

The PHP developers can easily upgrade to CakePHP 3.5.0 by running a simple composer command. But the latest version of CakePHP does not support certain methods. For instance, it requires programmers to use separate get/set methods instead of combined get/set methods. Hence, it becomes essential for PHP developers to know these deprecated methods and their replacements. The web application developers can further refer to the CakePHP 3.5 Migration Guide to upgrade to the latest version of the popular PHP framework smoothly.

 

-Major Features Of CakePHP

  • Build Quickly- Use code generation and scaffolding features to rapidly build prototypes.
  • No Configuration- No complicated XML or YAML files. Just setup your database and you’re ready to bake.
  • Friendly License- CakePHP is licensed under the MIT license which makes it perfect for use in commercial applications.
  • Batteries Included- The things you need are built-in. Translations, database access, caching, validation, authentication and much more are all built into one of the original PHP MVC frameworks.
  • Clean MVC Conventions- Instead of having to plan where things go, CakePHP comes with a set of conventions to guide you in developing your application.
  • Secure- CakePHP comes with built-in tools for input validation, CSRF protection, Form tampering protection, SQL injection prevention and XSS prevention, helping you keep your application safe & secure.

AWS

Installation Instructions For Ubuntu

Step 1) SSH Connection: To connect to the deployed instance, Please follow Instructions to Connect to Ubuntu instance on Azure Cloud

1) Download Putty.

2) Connect to virtual machine using following SSH credentials :

  • Hostname: PublicDNS  / IP of machine
  • Port : 22

Username: To connect to the operating system, use SSH and the username is ubuntu.
Password : Please Click here  to know how to  get password .

Step 2) Database Login Details :

  • MYSQL Username : root
  • MYSQL Password : Passw@rd123

Note :-Please change password immediately after first login.

Step 3) Application URL: Access the application via a browser at http://PublicDNS/Cakephp. 

Note: How to find PublicDNS in Azure

Step 4) Other Information:

1.Default installation path: will be in your web root folder “/var/www/html/cakephp”.

2.Default ports:

  • Linux Machines:  SSH Port – 22
  • Http: 80
  • Https: 443
  • Mysql ports: By default these are not open on Public Endpoints. Internally Mysql server: 3306


Configure custom inbound and outbound rules using this link

Installation Instructions for Windows

Note:  How to find PublicDNS in AWS

Step 1) RDP  Connection: To connect to the deployed instance, Please follow Instructions to Connect to Windows  instance on AWS Cloud

1) Connect to virtual machine using following RDP credentials :

  • Hostname: PublicDNS  / IP of machine
  • Port : 3389

Username: To connect to the operating system, use RDP and the username is Administrator.
Password : Please Click here  to know how to  get password .

Step 2) Database Login Details :

  • MYSQL Username : root
  • MYSQL Password : Passw@rd123

Please change the password immediately after the first login.

Step 3) Application URL: Access the application via a browser at http://PublicDNS/Cakephp

Step 4) Other Information:

1.Default installation path: will be in your web root folder “C:\inetpub\wwwroot\Cakephp
2.Default ports:

  • Windows Machines:  RDP Port – 3389
  • Http: 80
  • Https: 443
  • Mysql ports: By default these are not open on Public Endpoints. Internally Mysql server: 3306

Configure custom inbound and outbound rules using this link

AWS Step by Step Screenshots

Azure

Installation Instructions For Ubuntu

Version:- CakePHP 3.4.4

Note : How to find PublicDNS in Azure

Step 1) SSH Connection: To connect to the deployed instance, Please follow Instructions to Connect to Ubuntu instance on Azure Cloud

1) Download Putty.

2) Connect to virtual machine using following SSH credentials :

  • Hostname: PublicDNS  / IP of machine
  • Port : 22

Step 2) Database Login Details :

  • MYSQL Username : root
  • MYSQL Password : Passw@rd123

Note :-For Stack Database: DB cakephp with user cakephpuser and password Passw@rd123 has already been created.Please use this database for you Stack Configuration.
You can create a new cakephp application with below command
composer create-project –prefer-dist cakephp/app YourAppname
If you create a new app please change the path in Apache2 config

Note :-Please change password immediately after first login.

Step 3) Application URL: Access the application via a browser at http://PublicDNS/. 

Step 4) Other Information:
1.Default installation path: will be on your web root folder “/var/www/html/”.
2.Default ports:

    • Linux Machines:  SSH Port – 22
    • Http: 80
    • Https: 443
    • Sql or Mysql ports: By default these are not open on Public Endpoints. Internally Sql server: 1433. Mysql :3306


Configure custom inbound and outbound rules using this link

Installation Instructions for Windows

Note: How to find PublicDNS in Azure

Step1 ) RDP Connection: To connect to the deployed instance, Please follow Instructions to Connect to Windows instance on Azure Cloud

1) Connect to virtual machine using following RDP credentials :

  • Hostname: PublicDNS  / IP of machine
  • Port : 3389

Username: Your chosen username when you created the machine ( For example:  Azureuser)
Password : Your Chosen Password when you created the machine ( How to reset the password if you do not remember)

Step 2) Database Login Details :

  • MYSQL Username : root
  • MYSQL Password : Passw@rd123

Step 3) Application URL: Access the application via a browser at http://PublicDNS/Cakephp

Step 4) Other Information:

1.Default installation path: will be on your web root folder “C:\inetpub\wwwroot\Cakephp
2.Default ports:

  • Windows Machines:  RDP Port – 3389
  • Http: 80
  • Https: 443
  • Sql or Mysql ports: By default these are not open on Public Endpoints. Internally Sql server: 1433. Mysql :3306


Configure custom inbound and outbound rules using this link

Installation Instructions For CentOS 

Note : How to find PublicDNS in Azure

Step 1) SSH Connection: To connect to the deployed instance, Please follow Instructions to Connect to Centos instance on Azure Cloud

1) Download Putty.

2) Connect to virtual machine using following SSH credentials :

  • Hostname: PublicDNS  / IP of machine
  • Port : 22

Step 2) Database Login Details :

  • MYSQL Username : root
  • MYSQL Password : Passw@rd123

Note :-For Stack Database: DB cakephp with user cakephpuser and password Passw@rd123 has already been created.Please use this database for you Stack Configuration.

You can create a new cakephp application with below commands
cd /var/www/html
composer create-project –prefer-dist cakephp/app YourAppname
If you create a new app please change the path in Http config

Note :-Please change password immediately after first login.

Step 3) Application URL: Access the application via a browser at http://PublicDNS/. 

Step 4) Other Information:
1.Default installation path: will be on your web root folder “/var/www/html/”.
2.Default ports:

  • Linux Machines:  SSH Port – 22
  • Http: 80
  • Https: 443
  • Sql or Mysql ports: By default these are not open on Public Endpoints. Internally Sql server: 1433. Mysql :3306

Configure custom inbound and outbound rules using this link

Azure Step by Step Screenshots 

Google

Installation Instructions For Ubuntu

Installation Instructions for Ubuntu

Step 1) VM Creation:

  1. Click the Launch on Compute Engine button to choose the hardware and network settings.
  2. You can see at this page, an overview of Cognosys Image as well as estimated cost of running the instance.
  3. In the settings page, you can choose the number of CPUs and amount of RAM, the disk size and type etc.

Step 2) SSH Connection:To initialize the DB Server connect to the deployed instance, Please follow Instructions to Connect to Ubuntu instance on Google Cloud

1) Download Putty.

2) Connect to the virtual machine using SSH key

  • Hostname: PublicDNS  / IP of machine
  • Port : 22

Step 3) Database Login Details:

The below screen appears after successful deployment of the image.

successful deployment of the image

For local MySQL root password, please use the temporary password generated automatically during image creation as shown above.

i) Please connect to Remote Desktop as given in step 2 to ensure stack is properly configured and DB is initialized.
ii) You can use MySQL server instance as localhost, username root and password as shown above.

If you have closed the deployment page you can also get the MySQL root password from VM Details  “Custom metadata” Section.

Note: You shall see a error “CakePHP is NOT able to connect to the database.” You are required to enter the database and credentials information in /var/www/cakephp/config/app.php under Data-sources section
Please use MySQL root user with the password which was generated during the deployment to configure same.

Step 4) Application URL: Access the application via a browser at http://PublicDNS/Cakephp. 

Step 5) Other Information:

1.Default installation path: will be in your web root folder “/var/www/html/cakephp”.

2.Default ports:

  • Linux Machines:  SSH Port – 22
  • Http: 80
  • Https: 443
  • Mysql ports: By default these are not open on Public Endpoints. Internally Mysql server: 3306

Videos

Secured CakePHP on Windows 2012 R2

Secured cakephp on centos

CakePHP  Introduction & Installation

CakePHP on cloud

Related Posts