Read New Data From Database Mysql Cakephp

The author selected the Complimentary and Open up Source Fund to receive a donation as function of the Write for DOnations program.

Introduction

CakePHP is a pop and feature-rich PHP spider web framework. It solves many of the mutual bug in spider web evolution, such as interacting with a database, shielding against SQL injections, and generating view code. Information technology adheres to the model-view-controller (MVC) design, which decouples various parts of the application, effectively allowing developers to work on different parts of the app in parallel. It too provides built-in security and authentication. To create a basic database app is a seamless process, which makes CakePHP useful for prototyping. However, you can use CakePHP to create fully developed web applications for deployment as well.

In this tutorial, you will deploy an example CakePHP web awarding to a production environment. To achieve this, you lot'll prepare an instance database and user, configure Apache, connect your app to the database, and plough off debug way. You'll also utilize CakePHP's bake command to automatically generate commodity models.

Prerequisites

Earlier you lot begin this tutorial, you lot will need:

  • A server running Ubuntu 18.04 with root access and a sudo, non-root business relationship, y'all tin gear up this up by following this initial server setup guide.
  • A LAMP stack installed co-ordinate to How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 18.04. At the time of this writing, PHP 7.2 is the latest version.
  • Composer (a PHP package director) installed on your server. For a guide on how to do that, visit How To Install and Use Composer on Ubuntu 18.04. You only need to consummate the beginning two steps from that tutorial.
  • Apache secured with Permit's Encrypt. To complete this prerequisite, y'all'll first need to set upwards virtual hosts post-obit Step v of How To Install Apache on Ubuntu eighteen.04. You can and then follow How To Secure Apache with Let's Encrypt on Ubuntu xviii.04 to secure Apache with Let's Encrypt. When asked, enable mandatory HTTPS redirection.
  • A fully registered domain proper noun. This tutorial will use example.com throughout. You tin purchase a domain proper name on Namecheap, get one for free on Freenom, or use the domain registrar of your choice.
  • Both of the post-obit DNS records gear up for your server. You tin follow this introduction to DigitalOcean DNS for details on how to add together them.
    • An A record with example.com pointing to your server's public IP accost.
    • An A record with www.instance.com pointing to your server's public IP address.

Step i — Installing Dependencies

To prepare for your application, you'll begin by installing the PHP extensions that CakePHP needs.

Start off by updating the package managing director enshroud:

                      
  1. sudo apt update

CakePHP requires the mbstring, intl, and simplexml PHP extensions, which add support for multibyte strings, internationalization, and XML processing. Y'all take installed mbstring as office of the Composer prerequisite tutorial. You can install the remaining libraries with one command:

                      
  1. sudo apt install phpseven.two-intl php7.2-xml -y

Recollect that the version numbers above (vii.2) will change with new versions of PHP.

You installed the required dependencies for CakePHP. You're now ready to configure your MySQL database for product apply.

Step 2 — Setting Upwards a MySQL Database

Now, y'all'll create a MySQL database to store information nearly your weblog's articles. Y'all'll also create a database user that your application will use to access the database. You'll alter the database privileges to achieve this separation of control. Equally a result, bad actors won't be able to cause bug on the system even with database credentials, which is an important security precaution in a production surround.

Launch your MySQL shell:

                      
  1. sudo mysql -u root -p

When asked, enter the password you set up during the initial LAMP installation.

Next, create a database:

                      
  1. CREATE DATABASE cakephp_blog ;

You will see output like to:

                      

Output

Query OK, ane row affected (0.00 sec)

Your CakePHP app will use this new database to read and store product data.

And then, instruct MySQL to operate on the new cakephp_blog database:

                      
  1. USE cakephp_blog ;

You lot will see output similar to:

                      

Output

Database changed

At present you lot'll create a tabular array schema for your web log articles in the cakephp_blog database. Run the following command to set this up:

                      
  1. CREATE Table articles (
  2. id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  3. title VARCHAR( 50 ),
  4. torso TEXT,
  5. created DATETIME DEFAULT Naught,
  6. modified DATETIME DEFAULT Nothing
  7. ) ;

You've created a schema with v fields to describe blog articles:

  • id: is the unique identifier of an article, set up every bit a primary key.
  • title: is the title of an article, declared as a text field containing a maximum of 50 characters.
  • body: is the text of the article, declared as TEXT field.
  • created: is the engagement and time of a record'due south creation.
  • modified: is the appointment and time of a tape's modification.

The output will exist similar to:

                      

Output

Query OK, 0 rows affected (0.01 sec)

You have created a tabular array for storing articles in the cakephp_blog database. Next, populate it with example articles by running the post-obit control:

                      
  1. INSERT INTO articles (title, body, created)
  2. VALUES ( 'Sample title', 'This is the article torso.', NOW( )) ;

You've added an example article with some sample data for the title and torso text.

Yous will see the following output:

                      

Output

Query OK, 0 rows affected (0.01 sec)

In order to connect the CakePHP app to the database, you lot demand to create a new database user and restrict its privileges:

                      
  1. GRANT ALL PRIVILEGES ON cakephp_blog.* TO 'cake_user'@'localhost' IDENTIFIED Past 'password' ;

This command grants all privileges to all the tables in the database.

Remember to replace password with a strong password of your pick.

To update your database with the changes you lot've made, reload by running:

                      
  1. FLUSH PRIVILEGES;

Y'all've only created a new database user, cake_user and given the user privileges only on the cakephp_blog database, thus tightening security.

Exit the MySQL terminal past entering go out.

Y'all've created a new database with a schema, populated information technology with example information, and created an appropriate database user. In the next step, you lot will gear up the CakePHP app itself.

Step 3 — Creating the Blog Awarding

In this section, y'all'll utilize Composer to install an example CakePHP app. It is advantageous to use Composer as it allows you to install CakePHP from your command line and it automatically sets upward certain file permissions and configuration files.

Kickoff, navigate to the Apache web server folder:

                      
  1. cd /var/www/example.com/html

Apache uses this directory to store files visible to the outside world. The root user owns this directory, so your non-root user, sammy , can't write anything to it. To correct this, you'll change the file system permissions past running:

                      
  1. sudo chown -R sammy .

You'll now create a new CakePHP app via Composer:

                      
  1. composer create-project --prefer-dist cakephp/app cake-blog

Here yous accept invoked composer and instructed information technology to create a new project with create-project. --prefer-dist cakephp/app tells composer to use CakePHP every bit a template with cake-blog as the proper name of the new awarding.

Continue in mind that this command may take some fourth dimension to finish.

When Composer asks yous to fix binder permissions, answer with y.

In this section, you lot created a new CakePHP project with Composer. In the next footstep, you will configure Apache to point to the new app, which will make it viewable in your browser.

Step 4 — Configuring Apache to Point to Your App

At present, you'll configure Apache for your new CakePHP application, as well as enable .htaccess overriding, which is a CakePHP requirement. This entails editing Apache configuration files.

For actual routing to take place, yous must instruct Apache to use .htaccess files. These are configuration files that volition be in subdirectories of the awarding (where needed), and and then Apache uses the files to alter its global configuration for the requested part of the app. Amid other tasks, they will contain URL rewriting rules, which y'all'll be adjusting now.

Beginning off past opening the Apache global configuration file (apache2.conf) using your text editor:

                      
  1. sudo nano /etc/apache2/apache2.conf

Observe the post-obit block of code:

/etc/apache2/apache2.conf

          ... <Directory /var/www/>         Options Indexes FollowSymLinks         AllowOverride None         Require all granted </Directory> ...                  

Change AllowOverride from None to All, like the following:

/etc/apache2/apache2.conf

          ... <Directory /var/www/>         Options Indexes FollowSymLinks         AllowOverride            All            Require all granted </Directory> ...                  

Salvage and close the file.

Next, you will instruct Apache to bespeak to the webroot directory in the CakePHP installation. Apache stores its configuration files on Ubuntu 18.04 in /etc/apache2/sites-available. These files govern how Apache processes web requests.

During the Let's Encrypt prerequisite tutorial, you enabled HTTPS redirection; therefore only allowing HTTPS traffic. As a result, you'll just edit the example.com-le-ssl.conf file, which configures HTTPS traffic.

Beginning, open the example.com-le-ssl.conf configuration file:

                      
  1. sudo nano /etc/apache2/sites-bachelor/example.com-le-ssl.conf

You need to change just one line, the one that sets up DocumentRoot and tells Apache from where to serve content to the browser. Find the following line in the file:

/etc/apache2/sites-available/instance.com-le-ssl.conf

          DocumentRoot /var/www/example.com/html                  

Edit this line to betoken to the CakePHP installation, by calculation the post-obit highlighted content:

/etc/apache2/sites-bachelor/example.com-le-ssl.conf

          DocumentRoot /var/www/example.com/html/block-blog/webroot                  

Save the file and leave the editor.

Afterwards, restart Apache to reflect the new configuration:

                      
  1. sudo systemctl restart apache2

Now you tin can visit https://your_domain/ in your browser.

CakePHP can't connect to the database

You'll run across the default CakePHP success page. You'll find that there is a block indicating that your application can't connect to the database. In the next step you'll resolve this by connecting your app to the database.

You lot've now enabled .htaccess overriding, and pointed Apache to the right webroot directory.

Step 5 — Connecting Your App to the Database

In this department, yous will connect your database to your application so that your weblog can access the articles. You'll edit CakePHP's default config/app.php file to set up the connection to your database.

Navigate to the app folder:

                      
  1. cd /var/www/example.com/html/block-blog

Open the config/app.php file, by running the following command:

                      
  1. sudo nano config/app.php

Find the Datasources cake (it looks similar the following):

/var/world wide web/example.com/html/cake-weblog/config/app.php

          ...     'Datasources' => [         'default' => [             'className' => 'Cake\Database\Connection',             'driver' => 'Cake\Database\Driver\Mysql',             'persistent' => false,             'host' => 'localhost',             ...             //'port' => 'non_standard_port_number',             'username' => 'cake_user',             'password' => 'password',             'database' => 'cakephp_blog', ...                  

For 'username' replace my_app with your database user's username (this tutorial uses: cake_user ), secret with your database user'due south password, and the 2d my_app with the database name ( cakephp_blog in this tutorial).

Salvage and shut the file.

Refresh the app in your browser and observe the success bulletin under the Database section. If it shows an mistake, double check your configuration file against the preceding steps.

CakePHP can connect to the database

In this footstep, you've connected the CakePHP app to your MySQL database. In the next step, you lot'll generate the model, view, and controller files that will brand up the user interface for interacting with the articles.

Step vi — Creating the Commodity User Interface

In this section, you'll create a ready-to-apply article interface by running the CakePHP bake command, which generates the article model. In CakePHP, blistering generates all required models, views, and controllers in a basic state, fix for further development. Every database app must allow for create, read, update, and delete (CRUD) operations, which makes CakePHP's broil feature useful for automatically generating code for these operations. Within a couple of minutes, y'all get a full paradigm of the app, ready to enter, store, and edit the data.

Models, views, and controllers pertain to the MVC pattern. Their roles are:

  • Models stand for the information structure.
  • Views nowadays the data in a user-friendly fashion.
  • Controllers human activity upon user requests and serve as an intermediary between views and models.

CakePHP stores its CLI executable under bin/block. While it is mostly used for blistering, information technology offers a slew of other commands, such as the ones for clearing diverse caches.

The bake command volition cheque your database, and generate the models based on the table definitions information technology finds. Offset off past running the following command:

                      
  1. ./bin/cake broil all

By passing the all command, you are instructing CakePHP to generate models, controllers, and views all at once.

Your output volition await similar this:

                      

Output

Bake All --------------------------------------------------------------- Possible model names based on your database: - manufactures Run `cake bake all [name]` to generate skeleton files.

It has properly detected the articles definition from your database, and is offer to generate files for that model.

Bake information technology by running:

                      
  1. ./bin/cake bake all articles

Your output will expect like this:

                      

Output

Broil All --------------------------------------------------------------- 1 moment while associations are detected. Baking table class for Articles... Creating file /var/www/example.com/html/block-blog/src/Model/Table/ArticlesTable.php Wrote `/var/world wide web/example.com/html/cake-weblog/src/Model/Table/ArticlesTable.php` Deleted `/var/www/example.com/html/block-blog/src/Model/Table/empty` Baking entity course for Commodity... Creating file /var/www/case.com/html/cake-blog/src/Model/Entity/Commodity.php Wrote `/var/www/example.com/html/cake-blog/src/Model/Entity/Article.php` Deleted `/var/world wide web/example.com/html/cake-blog/src/Model/Entity/empty` Baking test fixture for Manufactures... Creating file /var/world wide web/case.com/html/cake-blog/tests/Fixture/ArticlesFixture.php Wrote `/var/www/instance.com/html/cake-blog/tests/Fixture/ArticlesFixture.php` Deleted `/var/www/example.com/html/block-web log/tests/Fixture/empty` Bake is detecting possible fixtures... Baking test instance for App\Model\Table\ArticlesTable ... Creating file /var/www/instance.com/html/cake-weblog/tests/TestCase/Model/Tabular array/ArticlesTableTest.php Wrote `/var/www/instance.com/html/cake-blog/tests/TestCase/Model/Table/ArticlesTableTest.php` Baking controller class for Articles... Creating file /var/www/example.com/html/cake-blog/src/Controller/ArticlesController.php Wrote `/var/world wide web/example.com/html/cake-blog/src/Controller/ArticlesController.php` Broil is detecting possible fixtures... ... Baking `add together` view template file... Creating file /var/www/example.com/html/block-web log/src/Template/Articles/add together.ctp Wrote `/var/www/example.com/html/cake-blog/src/Template/Articles/add.ctp` Blistering `edit` view template file... Creating file /var/www/example.com/html/cake-blog/src/Template/Manufactures/edit.ctp Wrote `/var/www/example.com/html/block-weblog/src/Template/Manufactures/edit.ctp` Bake All complete.

In the output, you volition see that CakePHP has logged all the steps it took to create a functional boilerplate for the manufactures database.

At present, navigate to the following in your browser:

          https://your_domain/articles                  

You'll see a list of articles currently in the database, which includes i row titled Sample Championship. The bake command created this interface allowing you to create, delete, and edit articles. As such, it provides a solid starting signal for further development. You tin can endeavor adding a new article past clicking the New Article link in the sidebar.

The generated article user interface

In this section, you generated model, view, and controller files with CakePHP's broil command. You can now create, delete, view, and edit your articles, with all your changes immediately saved to the database.

In the next step, you will disable the debug style.

Step 7 — Disabling Debug Mode in CakePHP

In this section, you volition disable the debug fashion in CakePHP. This is crucial because in debug mode the app shows detailed debugging data, which is a security take chances. You'll complete this step later you lot've completed the evolution of your application.

Open the config/app.php file using your favorite editor:

                      
  1. sudo nano config/app.php

Almost the start of the file in that location will be a line for the 'debug' way. When you open the file 'debug' mode will be set to true. Alter this to imitation as per the following:

config/app.php

                      ...            'debug'            =>            filter_var            (            env            (            'DEBUG'            ,                          false                        )            ,            FILTER_VALIDATE_BOOLEAN            )            ,            ...                  

Once yous've turned debug manner off, the dwelling page, located nether src/Templates/Pages/dwelling.ctp, will testify an error.

The debug mode error

Notation: If yous haven't inverse the default route or replaced the contents of habitation.ctp, the home page of your app will now show an error. This is because the default abode page serves as a status dashboard during development, but does not work with debug mode disabled.

You've disabled debug mode. Any errors and exceptions that occur from now, along with their stack traces, won't be shown to the finish user, tightening the security of your awarding.

However, afterward, disabling debug mode, your home.ctp will bear witness an error. If you lot've completed this step only for the purposes of this tutorial, you can now redirect your home page to the articles listing interface while keeping debug way disabled. Yous'll attain this by editing the contents of abode.ctp.

Open domicile.ctp for editing:

                      
  1. sudo nano src/Template/Pages/home.ctp

Supervene upon its contents with the following:

src/Template/Pages/home.ctp

                                                    <meta              http-equiv                              =                "refresh"                            content                              =                "0; url=./Manufactures"                            />                                                      <p              >                                                      <a              href                              =                "./Manufactures"                            >            Click here if you are not redirected                              </a              >                                                      </p              >                              

This HTML redirects to the Manufactures controller. If the automatic redirection fails, there is besides a link for users to follow.

In this step, y'all disabled debug way for security purposes and stock-still the abode page'south error by redirecting the user to the blog mail listing interface that the Articles controller provides.

Decision

You take now successfully ready a CakePHP application on a LAMP stack on Ubuntu 18.04. With CakePHP, you tin can create a database with equally many tables as you lot like, and it will produce a alive web editor for the data.

The CakePHP cookbook offers detailed documentation regarding every attribute of CakePHP. The side by side step for your application could include implementing user authentication then that every user tin can make their own articles.

simmonsvage1958.blogspot.com

Source: https://www.digitalocean.com/community/tutorials/how-to-set-up-a-cakephp-application-with-lamp-on-ubuntu-18-04

0 Response to "Read New Data From Database Mysql Cakephp"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel