Creating a user in M, V, C

First, create a database with a users table or collection, with at least a primary key (usually id or _id) and the fields username and password (these could of course be renamed, but that requires more configuration).

The Model

Create the model in models/Users.php:

  1. namespace app\models;
  2. class Users extends \lithium\data\Model {}

Then, create a model filter in a new bootstrap file in app/config/bootstrap/ called user.php. This file will automatically hash user passwords before the accounts are created. The Password class will automatically use the most secure hashing method available on your system:

  1. use app\models\Users;
  2. use lithium\aop\Filters;
  3. use lithium\security\Password;
  4. Filters::apply(Users::class, 'save', function($params, $next) {
  5. if ($params['data']) {
  6. $params['entity']->set($params['data']);
  7. $params['data'] = [];
  8. }
  9. if (!$params['entity']->exists()) {
  10. $params['entity']->password = Password::hash($params['entity']->password);
  11. }
  12. return $next($params);
  13. });
This example uses new-style filters, available with 1.1.

Now add the following line to app/config/bootstrap.php to include your new user.php bootstrap file.

  1. require __DIR__ . '/bootstrap/user.php';

The Controller

Create this file in controllers/UsersController:

  1. namespace app\controllers;
  2. use lithium\security\Auth;
  3. use app\models\Users;
  4. class UsersController extends \lithium\action\Controller {
  5. public function index() {
  6. $users = Users::all();
  7. return compact('users');
  8. }
  9. public function add() {
  10. $user = Users::create($this->request->data);
  11. if (($this->request->data) && $user->save()) {
  12. return $this->redirect('Users::index');
  13. }
  14. return compact('user');
  15. }
  16. }

The views

Then create the templates.

views/users/add.html.php:

  1. <h2>Add user</h2>
  2. <?= $this->form->create($user) ?>
  3. <?= $this->form->field('username') ?>
  4. <?= $this->form->field('password', ['type' => 'password']) ?>
  5. <?= $this->form->submit('Create me') ?>
  6. <?= $this->form->end() ?>

views/users/index.html.php:

  1. <h2>Users</h2>
  2. <ul>
  3. <?php foreach ($users as $user) { ?>
  4. <li><?= $user->username ?></li>
  5. <?php } ?>
  6. </ul>