CakePHP – Overview

CakePHP – Overview ”; Previous Next CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks. Advantages of CakePHP The advantages of using CakePHP are listed below − 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 Localisation 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 in CakePHP works − A typical CakePHP request cycle starts with a user requesting a page or resource in your application. At 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 and 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. Print Page Previous Next Advertisements ”;

CakePHP – Home

CakePHP Tutorial PDF Version Quick Guide Resources Job Search Discussion CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers guarantee a strict, but natural separation of business logic from data and presentation layers. Audience This tutorial is meant for web developers and students who would like to learn how to develop websites using CakePHP. It will provide a good understanding of how to use this framework. Prerequisites Before you proceed with this tutorial, we assume that you have knowledge of HTML, Core PHP, and Advance PHP. We have used CakePHP version 4.0.3 in all the examples. Print Page Previous Next Advertisements ”;

CakePHP – Project Configuration

CakePHP – Project Configuration ”; Previous Next In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP. Configuration CakePHP comes with one configuration file by default, and we can modify it according to our needs. There is one dedicated folder “config” for this purpose. CakePHP comes with different configuration options. Let us start by understanding the Environment Variables in CakePHP. Environment Variables Environment variables make the working of your application on different environments easy. For example, on dev server, test server, staging server and production server environment. For all these environments, you can make use of env() function to read the configuration for the environment you need and build your application. In your config folder, you will come across config/.env.example. This file has all the variables that will be changed based on your environment. To start with, you can create a file in config folder i.e. config/.env and define those variables and use them. In case you need any additional variables, it can go in that file. You can read your environment variable using env() function as shown below − Example $debug = env(”APP_DEBUG”, false); The first one is the name of the environment variable you want and second value is the default value. The default value is used, if there is no value found for the environment variable. General Configuration The following table describes the role of various variables and how they affect your CakePHP application. Sr.No Variable Name & Description 1 debug Changes CakePHP debugging output. false = Production mode. No error messages, errors, or warnings shown. true = Errors and warnings shown. 2 App.namespace The namespace to find app classes under. 3 App.baseUrl Un-comment this definition, if you don’t plan to use Apache’s mod_rewrite with CakePHP. Don’t forget to remove your .htaccess files too. 4 App.base The base directory the app resides in. If false, this will be auto detected. 5 App.encoding Define what encoding your application uses. This encoding is used to generate the charset in the layout, and encode entities. It should match the encoding values specified for your database. 6 App.webroot The webroot directory. 7 App.wwwRoot The file path to webroot. 8 App.fullBaseUrl The fully qualified domain name (including protocol) to your application’s root. 9 App.imageBaseUrl Web path to the public images directory under webroot. 10 App.cssBaseUrl Web path to the public css directory under webroot. 11 App.jsBaseUrl Web path to the public js directory under webroot. 12 App.paths Configure paths for non-class based resources. Supports the plugins, templates, locales, subkeys, which allow the definition of paths for plugins, view templates and locale files respectively. 13 Security.salt A random string used in hashing. This value is also used as the HMAC salt when doing symmetric encryption. 14 Asset.timestamp Appends a timestamp, which is last modified time of the particular file at the end of asset files URLs (CSS, JavaScript, Image) when using proper helpers. The valid values are − (bool) false – Doesn’t do anything (default). (bool) true – Appends the timestamp, when debug is true. (string) ‘force’ – Always appends the timestamp. Databases Configuration Database can be configured in config/app.php and config/app_local.php file. This file contains a default connection with provided parameters, which can be modified as per our choice. The below snippet shows the default parameters and values, which should be modified as per the requirement. Config/app_local.php */ ”Datasources” => [ ”default” => [ ”host” => ”localhost”, ”username” => ”my_app”, ”password” => ”secret”, ”database” => ”my_app”, ”url” => env(”DATABASE_URL”, null), ], /* * The test connection is used during the test suite. */ ”test” => [ ”host” => ”localhost”, //”port” => ”non_standard_port_number”, ”username” => ”my_app”, ”password” => ”secret”, ”database” => ”test_myapp”, //”schema” => ”myapp”, ], ], Let us understand each parameter in detail in config/app_local.php. Host The database server’s hostname (or IP address). username Database username password Database password. database Name of Database. Port The TCP port or Unix socket used to connect to the server. config/app.php ”Datasources” => [ ”default” => [ ”className” => Connection::class, ”driver” => Mysql::class, ”persistent” => false, ”timezone” => ”UTC”, //”encoding” => ”utf8mb4”, ”flags” => [], ”cacheMetadata” => true, ”log” => false, ”quoteIdentifiers” => false, //”init” => [”SET GLOBAL innodb_stats_on_metadata = 0”], ], ] Let us understand each parameter in detail in config/app.php. Sr.No Key & Description 1 className The fully namespaced class name of the class that represents the connection to a database server. This class is responsible for loading the database driver, providing SQL transaction mechanisms and preparing SQL statements among other things. 2 driver The class name of the driver used to implement all specificities for a database engine. This can either be a short classname using plugin syntax, a fully namespaced name, or a constructed driver instance. Examples of short classnames are Mysql, Sqlite, Postgres, and Sqlserver. 3 persistent Whether or not to use a persistent connection to the database. 4 encoding Indicates the character set to use, when sending SQL statements to the server like ‘utf8’ etc. 5 timezone Server timezone to set. 6 init A list of queries that should be sent to the database server as and when the connection is created. 7 log log Set to true to enable query logging. When enabled queries will be logged at a debug level with the queriesLog scope. 8 quoteIdentifiers Set to true, if you are using reserved words or special characters in your table or column names. Enabling this setting will result in queries built using the Query Builder having identifiers quoted when creating SQL. It decreases performance. 9 flags An associative array of PDO constants that should be passed to the underlying PDO instance. 10 cacheMetadata Either boolean true, or a string containing the cache configuration to store meta data in. Having metadata caching disable is not advised and can result in very poor performance. Email Configuration Email can be configured in file config/app.php. It is not required to define email configuration in config/app.php. Email can be used

CakePHP – View Events

CakePHP – View Events ”; Previous Next There are several callbacks/events that we can use with View Events. These events are helpful to perform several tasks before something happens or after something happens. The following is a list of callbacks that can be used with CakePHP − Sr.No Event Function & Description 1 Helper::beforeRender(Event $event,$viewFile) The beforeRender method is called after the controller’s beforeRender method but before the controller renders view and layout. This receives the file being rendered as an argument. 2 Helper::beforeRenderFile(Event $event, $viewFile) This method is called before each view file is rendered. This includes elements, views, parent views and layouts. 3 Helper::afterRenderFile(Event $event, $viewFile, $content) This method is called after each View file is rendered. This includes elements, views, parent views and layouts. A callback can modify and return $content to change how the rendered content will be displayed in the browser. 4 Helper::afterRender(Event $event, $viewFile) This method is called after the view has been rendered, but before the layout rendering has started. 5 Helper::beforeLayout(Event $event, $layoutFile) This method is called before the layout rendering starts. This receives the layout filename as an argument. 6 Helper::afterLayout(Event $event, $layoutFile) This method is called after the layout rendering is complete. This receives the layout filename as an argument. Print Page Previous Next Advertisements ”;

CakePHP – View Elements

CakePHP – View Elements ”; Previous Next Certain parts of the web pages are repeated on multiple web pages, but at different locations. CakePHP can help us reuse these repeated parts. These reusable parts are called Elements – help box, extra menu, etc. An element is basically a mini-view. We can also pass variables in elements. CakeViewView::element(string $elementPath, array $data, array $options =[] There are three arguments to the above function as follows − The first argument is the name of the template file in the /src/Template/element/ folder. The second argument is the array of data to be made available to the rendered view. The third argument is for the array of options. e.g. cache. Out of the 3 arguments, the first one is compulsory, while the rest are optional. Example Create an element file at src/Template/element directory called helloworld.php. Copy the following code in that file. src/Template/element/helloworld.php <p>Hello World</p> Create a folder Elems at src/Template and under that directory create a View file called index.php. Copy the following code in that file. src/Template/Elems/index.php Element Example: <?php echo $this->element(”helloworld”); ?> Make Changes in the config/routes.php file as shown in the following program. config/routes.php <?php use CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope(”/”, function (RouteBuilder $builder) { $builder->registerMiddleware(”csrf”, new CsrfProtectionMiddleware([ ”httpOnly” => true, ])); $builder->applyMiddleware(”csrf”); $builder->connect(”/element-example”,[”controller”=>”Elems”,”action”=>”index”]); $builder->fallbacks(); }); Create an ElemsController.php file at src/Controller/ElemsController.php. Copy the following code in the controller file. src/Controller/ElemsController.php <?php namespace AppController; use AppControllerAppController; class ElemsController extends AppController{ public function index(){ } } ?> Execute the above example by visiting the following URL http://localhost/cakephp4/element-example Output Upon execution, the above URL will give you the following output. Print Page Previous Next Advertisements ”;

CakePHP – Folder Structure

CakePHP – Folder Structure ”; Previous Next Here, we will learn about the Folder structure and the Naming Convention in CakePHP. Let us begin by understanding the Folder structure. Folder Structure Take a look at the following screenshot. It shows the folder structure of CakePHP. The following table describes the role of each folder in CakePHP − Sr.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 of your application uses are stored. 5 resources The files for internationalization in the respective locale folder will be stored here. E.g. locales/en_US. 6 src The src folder will be where you work your magic. It is where your application’s files will be placed and 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. Model − Contains your application’s tables, entities and behaviors. View Presentational classes are placed here: cells, helpers, and template files. 7 templates Template Presentational files are placed here: elements, error pages, layouts, and view template files. 8 tests The tests folder will be where you put the test cases for your application. 9 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. 10 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. 11 webroot The webroot directory is the public document root of your application. It contains all the files you want to be publically reachable. Naming Convention Naming convention is not something mandatory to be followed, but is a good coding practice and will be very helpful as your project goes big. Controller Convention The controller class name has to be plural, PascalCased and the name has to end with Controller. For example, for Students class the name of the controller can be StudentsController. Public methods on Controllers are often exposed as ‘actions’ accessible through a web browser. For example, the /users /view maps to the view() method of the UsersController out of the box. Protected or private methods cannot be accessed with routing. File and Class Name Convention Mostly, we have seen that our class name file name is almost the same. This is similar in cakephp. For example, the class StudentsController will have the file named as StudentsController.php. The files have to be saved as the module name and in the respective folders in app folder. Database Conventions The tables used for CakePHP models, mostly have names plural with underscore. For example, student_details, student_marks. The field name has an underscore, if it is made up of two words, for example, first_name, last_name. Model Conventions For model, the classes are named as per database table, the names are plural, PascalCased and suffixed with Table. For example, StudentDetailsTable, StudentMarksTable View Conventions For view templates, the files are based on controller functions. For example, if the class StudentDetailsController has function showAll(), the view template will be named as show_all.php and saved inside template/yrmodule/show_all.php. Print Page Previous Next Advertisements ”;