Page 1

1


Introduction

CakePHP is a framework under the MIT license, offers tools to

quickly develop

web applications in PHP language. The framework implements the Model View Controller

architectural pattern.

The Model layer is responsible for retrieving, processing, validating and associating data. The View layer is responsible for producing the interfaces of the application. The Controller layer handles requests from users and renders a response with the aid of both layers.

The main features of the framework are: ●

Build quickly: use code generation and scaffold command to build prototypes.

No configuration: just need to set up your database.

Conventions: to guide you and make easier the process of developing your app.

Secure: tools for SQL injection prevention.

In this tutorial, we are going to make a CRUD web application in order to add, show, update and delete students from a MySQL database. 2


2. Content 2.1 Requirements The minimum requirements for installing CakePHP are: ● Server ○ Apache ● PHP version 5.6.0 o bigger ● Database ○ MySQL ● Composer: tool for installing CakePHP in a simple way from the command line. Link for Windows: https://github.com/composer/windows-setup/releases/ 2.2 Create a new project After installing Composer you need to go to the directory where you want to create the application, and run the following command: ●

composer create-project -prefer-dist cakephp/app [appName]

The project directory should be: /appName /config /logs /src /plugins /tests /tmp /vendor /webroot .gitignore .htaccess .travis.yml README.md composer.json phpunit.xml.dist

3


2.3 Create the database ●

In this tutorial, we are going to make a CRUD web application, so we need to create a database with two tables (belongsTo/hasOne): CREATE TABLE students( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(45) NOT NULL, last_name VARCHAR(45) NOT NULL, date DATE NOT NULL, sex VARCHAR(45) NOT NULL, career VARCHAR(45) NOT NULL, semester INT NOT NULL );

CREATE TABLE users( id INT AUTO_INCREMENT PRIMARY KEY, user VARCHAR(45) NOT NULL, password VARCHAR(45) NOT NULL, student_id INT NOT NULL, FOREIGN KEY student_key (student_id) REFERENCES students(id) );

Conventions of CakePHP for the database: ● The names of the tables should be in plural (students and users) to automatically link the tables with the models. ● The id of the table should necessarily be “id”. ● The name of the foreign key should be the name in singular form of the related table followed by _id, for example: student_id.

2.4 Setup the database To setup the database in the CakePHP application you should: ● Open the app.php file in the project directory config/app.php. ● After that, go to the Datasources matrix and change the username, password and database values with the values of your own database.

4


'Datasources' => [ 'default' => [ 'className' => 'Cake\Database\Connection', 'driver' => 'Cake\Database\Driver\Mysql', 'persistent' => false, 'host' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'sra', 'encoding' => 'utf8', 'timezone' => 'UTC', 'flags' => [], 'cacheMetadata' => true, 'log' => false, ... ],

â—?

Save the changes and open the app, you should get the following view in your web browser.

5


2.5 Create models for the Students and Users tables â—?

Create the file StudentsTable.php in the project directory src/Model/Table and add the following:

<?php namespace App\Model\Table; use Cake\ORM\Table; class StudentsTable extends Table { public function initialize(array $config) { $this->setTable('students'); $this->setPrimaryKey('id'); $this->hasOne('Users', ['foreignKey' => 'student_id'] ); } } ?>

Create the UsersTable.php in the project directory src/Model/Table and add the following:

â&#x2014;?

<?php namespace App\Model\Table; use Cake\ORM\Table; class UsersTable extends Table { public function initialize(array $config) { $this->setTable('users'); $this->setPrimaryKey('id'); $this->belongsTo('Students', ['foreignKey' => 'student_id',]); } } ?>

6


2.6 Create the controller Students ●

Create the file StudentsController.php in the project directory src/Controller/Table and add the index action:

<?php namespace App\Controller; use App\Controller\AppController; class StudentsController extends AppController { public function index() { $students = $this->Students->find('all'); $this->set(compact('students')); } } ?>

2.7 Create the views for Students The next step is to create the view for the index action. It is important to save the file with the same name of the action, so that CakePHP knows what view should be rendered. 1. Create a new folder called Students in the project directory /src/Template 2. Create the index.ctp (ctp: cake template) inside of the folder Students that you previously created, and add the following: <h3> Sistema de Registro de Alumnos </h3> <table cellpadding="0" cellspacing="0"> <thead> <tr> <th> Nombre </th> <th> Apellidos </th> <th> Carrera </th> </tr> </thead> <tbody> <?php foreach ($students as $student): ?> <tr> <td> <?= ($student->nombre) ?> </td> <td> <?= ($student->apellidos) ?> </td> <td> <?= ($student->carrera) ?> </td> <td> <?= $this->Html->link(__('Visualizar'), ['action' => 'view', $student->id]) ?> </td> <td> <?= $this->Html->link(__('Editar'), ['action' => 'edit', $student->id]) ?> </td> <td> <?= $this->Form->postLink(__('Eliminar'), ['action' => 'delete', $student->id], ['confirm' => __('¿Está seguro de eliminar al alumno?')]) ?> </td> </tr> <?php endforeach; ?> </tbody> </table>

7


3. Now, if you go to route sra/alumnos/index you should get the following view, you will not get anything if you donâ&#x20AC;&#x2122;t have any data in your database.

4. The next step consists in create the view to add new students. Create the add.ctp file in the project directory src/Template/Students and add the following: <?= $this->Form->create($alumno) ?> <?php echo $this->Form->control('nombre'); echo $this->Form->control('apellidos'); echo $this->Form->control('fecha'); echo $this->Form->control('sexo'); echo $this->Form->control('carrera'); echo $this->Form->control('semestre'); echo $this->Form->control('usuario'); echo $this->Form->control('password'); ?> <?= $this->Form->button(__('Guardar')) ?> <?= $this->Form->end() ?>

5. Also, you need to add the validation rules in order to validate the inputs of the form. Add the following function in the StudentsController.php file: public function validationDefault(Validator $validator) { $validator->scalar('nombre')->notEmpty('nombre'); $validator->scalar('apellidos')->notEmpty('apellidos'); $validator->date('fecha')->notEmpty('fecha'); $validator->scalar('sexo')->notEmpty('sexo'); $validator->scalar('carrera')->notEmpty('carrera'); $validator->integer('semestre')->notEmpty('semestre'); $validator->scalar('usuario')->notEmpty('usuario'); $validator->scalar('password')->notEmpty('password'); return $validator; }

8


6. Then, add the add action in the StudentsController file, now you should be able to add new students in the route /appName/students/add : public function add() { $alumno = $this->Alumnos->newEntity(); if ($this->request->is('post')) { $datos = $this->request->getData(); $alumno = $this->Alumnos->patchEntity($alumno, $this->request->getData()); if ($this->Alumnos->save($alumno)) { $usuariosTable = TableRegistry::get('Usuarios'); $usuario = $usuariosTable->newEntity(); $usuario->usuario =$datos["usuario"]; $usuario->password = $datos["password"]; $usuario->alumno_id = $alumno->get('id'); if ($usuariosTable->save($usuario)) { $this->Flash->success(__('El alumno se agregรณ correctamente.')); return $this->redirect(['action' => 'index']); } } $this->Flash->error(__('El alumno no se agregรณ, intenta de nuevo')); } $this->set('alumno', $alumno); }

7. The next step is to display all the information of each student. To do that, add the view action in the StudentsController file: public function index(){ . . . public function add(){ . . .

} }

public function view($id = null) { $alumno = $this->Alumnos->get($id, [ 'contain' => ['Usuarios']]); $this->set('alumno', $alumno); }

8. We are still missing the view for the view action. You need to add the view.ctp file in the project directory src/Templates/Students: <div class="large-9 medium-6 columns content"> <h4>Informaci&oacute;n del alumno</h4> <table class="vertical-table"> <tr> <th>Nombre: </th> <td><?= ($alumno->nombre) ?></td> </tr> ... <tr> <th>Fecha de nacimiento:</th> <td><?= h($alumno->fecha) ?></td> </tr> </table> </div>

9


9. In order to edit the information of the students, you have to add the edit action in the StudentsController file: public function index(){ . . . } public function add(){ . . . } public function view($id = null) { ... } public function edit($id = null) { $alumno = $this->Alumnos->get($id); if ($this->request->is(['patch', 'post', 'put'])) { $alumno = $this->Alumnos->patchEntity($alumno, $this->request->getData()); if ($this->Alumnos->save($alumno)) { $this->Flash->success(__('La inf del alumno editada.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('El alumno no se agregรณ, intenta de nuevo')); } $this->set('alumno', $alumno); }

10. And create the edit.ctp src/Template/Students

file

in

the

project

directory

<div class="large-9 medium-8 columns content"> <?= $this->Form->create($alumno) ?> <fieldset> <legend> Editar informaci&oacute;n del alumno</legend> <?php echo $this->Form->control('nombre'); echo $this->Form->control('apellidos'); echo $this->Form->control('fecha'); echo $this->Form->control('sexo'); echo $this->Form->control('carrera'); echo $this->Form->control('semestre'); ?> </fieldset> <?= $this->Form->button(__('Guardar')) ?> <?= $this->Form->end() ?> </div>

11. Finally, to delete students you just need to add the delete action in the StudentsController file. The view for this action is not necessary because when a student is deleted, you should be redirected to the index view.

10


public function index() { . . . } public function view($id = null) { . . . } public function edit($id = null) { . . . } public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $alumno = $this->Alumnos->get($id); if ($this->Alumnos->delete($alumno)) { $this->Flash->success(__('El alumno se ha eliminado')); } else { $this->Flash->error(__('El alumno no se eliminó, intenta de nuevo')); } return $this->redirect(['action' => 'index']); }

References

Cake

Software

Foundation.

(2018,

April

05).

CakePHP.

Retrieved

from

Retrieved

from

Retrieved

from

https://book.cakephp.org/3.0/es/tutorials-and-examples/blog/blog.html ●

Cake

Software

Foundation.

(2018,

April

05).

CakePHP.

https://book.cakephp.org/3.0/es/tutorials-and-examples/blog/part-two.html ●

Cake

Software

Foundation.

(2018,

April

05).

CakePHP.

https://book.cakephp.org/3.0/es/tutorials-and-examples/blog/part-three.htm ●

Cake

Software

Foundation.

(2018,

April

05).

CakePHP.

Retrieved

from

05).

CakePHP.

Retrieved

from

https://book.cakephp.org/3.0/es/installation.html ●

Cake

Software

Foundation.

(2018,

April

https://book.cakephp.org/3.0/en/orm/database-basics.html ●

Yost,

J.

(2018,

April

05).

Lynda.

Retrieved

from

https://www.lynda.com/CakePHP-tutorials/CakePHP-3-Essential-Training/452749-2.htm

11

CakePHP CRUD  

CakePHP is a framework under the MIT license, offers tools to quickly develop web applications in PHP language. The framework implements th...

CakePHP CRUD  

CakePHP is a framework under the MIT license, offers tools to quickly develop web applications in PHP language. The framework implements th...

Advertisement