Skip to content

Dynamic pages

John Bent edited this page Jul 18, 2020 · 1 revision

To create a new page that uses information from the database, first, make sure you have your table already defined in MySQL (which is the database we use for this project).

CakePHP follows the Model–View–Controller (MVC) software design pattern commonly used for developing user interfaces that divide the related program logic into three interconnected elements. This is done to separate internal representations of information from the ways information is presented to and accepted from the user.

As long as you have a table already defined in your database, the framework will bake the baseline MVC templates for it so you can modify it according to your needs. For that, you can issue this command in the root of the project:

bin/cake bake

You should see something like:

$ bin/cake bake

Welcome to CakePHP v3.4.6 Console
---------------------------------------------------------------
App : src
Path: /var/www/cakephp.dev/src/
PHP : 5.6.20
---------------------------------------------------------------
The following commands can be used to generate skeleton code for your application.

Available bake commands:

- all
- behavior
- cell
- component
- controller
- fixture
- form
- helper
- mailer
- migration
- migration_diff
- migration_snapshot
- model
- plugin
- seed
- shell
- shell_helper
- task
- template
- test

By using `cake bake [name]` you can invoke a specific bake task.

For illustration purposes, we will create a new page for the contributors. Thus it should be called contributors. The convention is to have the table name in the plural. You can bake the new files for your table:

$ bin/cake bake all contributors

It will generate several files, the one you probably want to edit are:

  • src/Controller/ContributorsController.php
  • src/Model/Entity/Contributor.php (notice that here we are talking about one entry, so singular form)
  • src/Model/Table/ContributorsTable.php
  • templates/Contributors/ (this directory contains several files, one for each method/page in the Controller)

To create a new page to list contributors, for instance, you need to edit the src/Controller/ContributorsController.php by creating a function.

/**
 * List method
 *
 * @return \Cake\Http\Response|null|void Renders view
 */
public function list()
{
    $records = $this->paginate($this->Records);

    $this->set(compact('records'));
}

In practice, each function is converted into a page. You also need the template file to display that page with the same name as its function, e.g., templates/Contributors/list.php.

Clone this wiki locally