CMS Tutorial - Tags and Users

With the basic article creation functionality built, we need to enable multipleauthors to work in our CMS. Previously, we built all the models, views andcontrollers by hand. This time around we’re going to useBake Console to create our skeleton code. Bake is a powerfulcode generation CLI tool that leverages theconventions CakePHP uses to create skeleton CRUD applications very efficiently. We’re going to use bake to build ourusers code:

  1. cd /path/to/our/app
  2.  
  3. bin/cake bake model users
  4. bin/cake bake controller users
  5. bin/cake bake template users

These 3 commands will generate:

  • The Table, Entity, Fixture files.
  • The Controller
  • The CRUD templates.
  • Test cases for each generated class.

Bake will also use the CakePHP conventions to infer the associations, andvalidation your models have.

Adding Tagging to Articles

With multiple users able to access our small CMS it would be nice tohave a way to categorize our content. We’ll use tags and tagging to allow usersto create free-form categories and labels for their content. Again, we’ll usebake to quickly generate some skeleton code for our application:

  1. # Generate all the code at once.
  2. bin/cake bake all tags

Once you have the scaffold code created, create a few sample tags by going tohttp://localhost:8765/tags/add.

Now that we have a Tags table, we can create an association between Articles andTags. We can do so by adding the following to the initialize method on theArticlesTable:

  1. public function initialize(array $config): void
  2. {
  3. $this->addBehavior('Timestamp');
  4. $this->belongsToMany('Tags'); // Add this line
  5. }

This association will work with this simple definition because we followedCakePHP conventions when creating our tables. For more information, readAssociations - Linking Tables Together.

Updating Articles to Enable Tagging

Now that our application has tags, we need to enable users to tag theirarticles. First, update the add action to look like:

  1. // in src/Controller/ArticlesController.php
  2.  
  3. namespace App\Controller;
  4.  
  5. use App\Controller\AppController;
  6.  
  7. class ArticlesController extends AppController
  8. {
  9. public function add()
  10. {
  11. $article = $this->Articles->newEmptyEntity();
  12. if ($this->request->is('post')) {
  13. $article = $this->Articles->patchEntity($article, $this->request->getData());
  14.  
  15. // Hardcoding the user_id is temporary, and will be removed later
  16. // when we build authentication out.
  17. $article->user_id = 1;
  18.  
  19. if ($this->Articles->save($article)) {
  20. $this->Flash->success(__('Your article has been saved.'));
  21. return $this->redirect(['action' => 'index']);
  22. }
  23. $this->Flash->error(__('Unable to add your article.'));
  24. }
  25. // Get a list of tags.
  26. $tags = $this->Articles->Tags->find('list');
  27.  
  28. // Set tags to the view context
  29. $this->set('tags', $tags);
  30.  
  31. $this->set('article', $article);
  32. }
  33.  
  34. // Other actions
  35. }

The added lines load a list of tags as an associative array of id => title.This format will let us create a new tag input in our template.Add the following to the PHP block of controls in templates/Articles/add.php:

  1. echo $this->Form->control('tags._ids', ['options' => $tags]);

This will render a multiple select element that uses the $tags variable togenerate the select box options. You should now create a couple new articlesthat have tags, as in the following section we’ll be adding the ability to findarticles by tags.

You should also update the edit method to allow adding or editing tags. Theedit method should now look like:

  1. public function edit($slug)
  2. {
  3. $article = $this->Articles
  4. ->findBySlug($slug)
  5. ->contain('Tags') // load associated Tags
  6. ->firstOrFail();
  7. if ($this->request->is(['post', 'put'])) {
  8. $this->Articles->patchEntity($article, $this->request->getData());
  9. if ($this->Articles->save($article)) {
  10. $this->Flash->success(__('Your article has been updated.'));
  11. return $this->redirect(['action' => 'index']);
  12. }
  13. $this->Flash->error(__('Unable to update your article.'));
  14. }
  15.  
  16. // Get a list of tags.
  17. $tags = $this->Articles->Tags->find('list');
  18.  
  19. // Set tags to the view context
  20. $this->set('tags', $tags);
  21.  
  22. $this->set('article', $article);
  23. }

Remember to add the new tags multiple select control we added to the add.phptemplate to the templates/Articles/edit.php template as well.

Finding Articles By Tags

Once users have categorized their content, they will want to find that contentby the tags they used. For this feature we’ll implement a route, controlleraction, and finder method to search through articles by tag.

Ideally, we’d have a URL that looks likehttp://localhost:8765/articles/tagged/funny/cat/gifs. This would let usfind all the articles that have the ‘funny’, ‘cat’ or ‘gifs’ tags. Before wecan implement this, we’ll add a new route. Your config/routes.php shouldlook like:

  1. <?php
  2. use Cake\Http\Middleware\CsrfProtectionMiddleware;
  3. use Cake\Routing\RouteBuilder;
  4. use Cake\Routing\Router;
  5. use Cake\Routing\Route\DashedRoute;
  6.  
  7. Router::defaultRouteClass(DashedRoute::class);
  8.  
  9. Router::scope('/', function (RouteBuilder $routes) {
  10. // Register scoped middleware for in scopes.
  11. $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware([
  12. 'httpOnly' => true
  13. ]));
  14. $routes->applyMiddleware('csrf');
  15. $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
  16. $routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
  17. $routes->fallbacks(DashedRoute::class);
  18. });
  19. // Add this
  20. // New route we're adding for our tagged action.
  21. // The trailing `*` tells CakePHP that this action has
  22. // passed parameters.
  23. Router::scope('/articles', function (RouteBuilder $routes) {
  24. $routes->connect('/tagged/*', ['controller' => 'Articles', 'action' => 'tags']);
  25. });

The above defines a new ‘route’ which connects the /articles/tagged/ path,to ArticlesController::tags(). By defining routes, you can isolate how yourURLs look, from how they are implemented. If we were to visithttp://localhost:8765/articles/tagged, we would see a helpful error pagefrom CakePHP informing you that the controller action does not exist. Let’simplement that missing method now. In src/Controller/ArticlesController.phpadd the following:

  1. public function tags()
  2. {
  3. // The 'pass' key is provided by CakePHP and contains all
  4. // the passed URL path segments in the request.
  5. $tags = $this->request->getParam('pass');
  6.  
  7. // Use the ArticlesTable to find tagged articles.
  8. $articles = $this->Articles->find('tagged', [
  9. 'tags' => $tags
  10. ]);
  11.  
  12. // Pass variables into the view template context.
  13. $this->set([
  14. 'articles' => $articles,
  15. 'tags' => $tags
  16. ]);
  17. }

To access other parts of the request data, consult the Requestsection.

Since passed arguments are passed as method parameters, you could also write theaction using PHP’s variadic argument:

  1. public function tags(...$tags)
  2. {
  3. // Use the ArticlesTable to find tagged articles.
  4. $articles = $this->Articles->find('tagged', [
  5. 'tags' => $tags
  6. ]);
  7.  
  8. // Pass variables into the view template context.
  9. $this->set([
  10. 'articles' => $articles,
  11. 'tags' => $tags
  12. ]);
  13. }

Creating the Finder Method

In CakePHP we like to keep our controller actions slim, and put most of ourapplication’s logic in the model layer. If you were to visit the/articles/tagged URL now you would see an error that the findTagged()method has not been implemented yet, so let’s do that. Insrc/Model/Table/ArticlesTable.php add the following:

  1. // add this use statement right below the namespace declaration to import
  2. // the Query class
  3. use Cake\ORM\Query;
  4.  
  5. // The $query argument is a query builder instance.
  6. // The $options array will contain the 'tags' option we passed
  7. // to find('tagged') in our controller action.
  8. public function findTagged(Query $query, array $options)
  9. {
  10. $columns = [
  11. 'Articles.id', 'Articles.user_id', 'Articles.title',
  12. 'Articles.body', 'Articles.published', 'Articles.created',
  13. 'Articles.slug',
  14. ];
  15.  
  16. $query = $query
  17. ->select($columns)
  18. ->distinct($columns);
  19.  
  20. if (empty($options['tags'])) {
  21. // If there are no tags provided, find articles that have no tags.
  22. $query->leftJoinWith('Tags')
  23. ->where(['Tags.title IS' => null]);
  24. } else {
  25. // Find articles that have one or more of the provided tags.
  26. $query->innerJoinWith('Tags')
  27. ->where(['Tags.title IN' => $options['tags']]);
  28. }
  29.  
  30. return $query->group(['Articles.id']);
  31. }

We just implemented a custom finder method. This isa very powerful concept in CakePHP that allows you to package up re-usablequeries. Finder methods always get a Query Builder object and anarray of options as parameters. Finders can manipulate the query and add anyrequired conditions or criteria. When complete, finder methods must returna modified query object. In our finder we’ve leveraged the distinct() andleftJoin() methods which allow us to find distinct articles that havea ‘matching’ tag.

Creating the View

Now if you visit the /articles/tagged URL again, CakePHP will show a new errorletting you know that you have not made a view file. Next, let’s build theview file for our tags() action. In templates/Articles/tags.phpput the following content:

  1. <h1>
  2. Articles tagged with
  3. <?= $this->Text->toList(h($tags), 'or') ?>
  4. </h1>
  5.  
  6. <section>
  7. <?php foreach ($articles as $article): ?>
  8. <article>
  9. <!-- Use the HtmlHelper to create a link -->
  10. <h4><?= $this->Html->link(
  11. $article->title,
  12. ['controller' => 'Articles', 'action' => 'view', $article->slug]
  13. ) ?></h4>
  14. <span><?= h($article->created) ?></span>
  15. </article>
  16. <?php endforeach; ?>
  17. </section>

In the above code we use the Html andText helpers to assist in generating our view output. Wealso use the h shortcut function to HTML encode output. You shouldremember to always use h() when outputting data to prevent HTML injectionissues.

The tags.php file we just created follows the CakePHP conventions for viewtemplate files. The convention is to have the template use the lower case andunderscored version of the controller action name.

You may notice that we were able to use the $tags and $articlesvariables in our view template. When we use the set() method in ourcontroller, we set specific variables to be sent to the view. The View will makeall passed variables available in the template scope as local variables.

You should now be able to visit the /articles/tagged/funny URL and see allthe articles tagged with ‘funny’.

Improving the Tagging Experience

Right now, adding new tags is a cumbersome process, as authors need topre-create all the tags they want to use. We can improve the tag selection UI byusing a comma separated text field. This will let us give a better experience toour users, and use some more great features in the ORM.

Adding a Computed Field

Because we’ll want a simple way to access the formatted tags for an entity, wecan add a virtual/computed field to the entity. Insrc/Model/Entity/Article.php add the following:

  1. // add this use statement right below the namespace declaration to import
  2. // the Collection class
  3. use Cake\Collection\Collection;
  4.  
  5. // Update the accessible property to contain `tag_string`
  6. protected $_accessible = [
  7. //other fields...
  8. 'tag_string' => true
  9. ];
  10.  
  11. protected function _getTagString()
  12. {
  13. if (isset($this->_properties['tag_string'])) {
  14. return $this->_properties['tag_string'];
  15. }
  16. if (empty($this->tags)) {
  17. return '';
  18. }
  19. $tags = new Collection($this->tags);
  20. $str = $tags->reduce(function ($string, $tag) {
  21. return $string . $tag->title . ', ';
  22. }, '');
  23. return trim($str, ', ');
  24. }

This will let us access the $article->tag_string computed property. We’lluse this property in controls later on.

Updating the Views

With the entity updated we can add a new control for our tags. Intemplates/Articles/add.php and templates/Articles/edit.php,replace the existing tags._ids control with the following:

  1. echo $this->Form->control('tag_string', ['type' => 'text']);

We’ll also need to update the article view template. Insrc/Template/Articles/view.php add the line as shown:

  1. <!-- File: templates/Articles/view.php -->
  2.  
  3. <h1><?= h($article->title) ?></h1>
  4. <p><?= h($article->body) ?></p>
  5. // Add the following line
  6. <p><b>Tags:</b> <?= h($article->tag_string) ?></p>

Persisting the Tag String

Now that we can view existing tags as a string, we’ll want to save that data aswell. Because we marked the tag_string as accessible, the ORM will copy thatdata from the request into our entity. We can use a beforeSave() hook methodto parse the tag string and find/build the related entities. Add the followingto src/Model/Table/ArticlesTable.php:

  1. public function beforeSave($event, $entity, $options)
  2. {
  3. if ($entity->tag_string) {
  4. $entity->tags = $this->_buildTags($entity->tag_string);
  5. }
  6.  
  7. // Other code
  8. }
  9.  
  10. protected function _buildTags($tagString)
  11. {
  12. // Trim tags
  13. $newTags = array_map('trim', explode(',', $tagString));
  14. // Remove all empty tags
  15. $newTags = array_filter($newTags);
  16. // Reduce duplicated tags
  17. $newTags = array_unique($newTags);
  18.  
  19. $out = [];
  20. $query = $this->Tags->find()
  21. ->where(['Tags.title IN' => $newTags]);
  22.  
  23. // Remove existing tags from the list of new tags.
  24. foreach ($query->extract('title') as $existing) {
  25. $index = array_search($existing, $newTags);
  26. if ($index !== false) {
  27. unset($newTags[$index]);
  28. }
  29. }
  30. // Add existing tags.
  31. foreach ($query as $tag) {
  32. $out[] = $tag;
  33. }
  34. // Add new tags.
  35. foreach ($newTags as $tag) {
  36. $out[] = $this->Tags->newEntity(['title' => $tag]);
  37. }
  38. return $out;
  39. }

If you now create or edit articles, you should be able to save tags as a commaseparated list of tags, and have the tags and linking records automaticallycreated.

While this code is a bit more complicated than what we’ve done so far, it helpsto showcase how powerful the ORM in CakePHP is. You can manipulate queryresults using the Collections methods, and handlescenarios where you are creating entities on the fly with ease.

Auto-populating the Tag String

Before we finish up, we’ll need a mechanism that will load the associated tags(if any) whenever we load an article.

In your src/Model/Table/ArticlesTable.php, change:

  1. public function initialize(array $config): void
  2. {
  3. $this->addBehavior('Timestamp');
  4. // Change this line
  5. $this->belongsToMany('Tags', [
  6. 'joinTable' => 'articles_tags',
  7. 'dependent' => true
  8. ]);
  9. }

This will tell the Articles table model that there is a join table associatedwith tags. The ‘dependent’ option tells the table to delete any associatedrecords from the join table if an article is deleted.

Lastly, update the findBySlug() method calls insrc/Controller/ArticlesController.php:

  1. public function edit($slug)
  2. {
  3. // Update this line
  4. $article = $this->Articles->findBySlug($slug)->contain(['Tags'])
  5. ->firstOrFail();
  6. ...
  7. }
  8.  
  9. public function view($slug = null)
  10. {
  11. // Update this line
  12. $article = $this->Articles->findBySlug($slug)->contain(['Tags'])
  13. ->firstOrFail();
  14. $this->set(compact('article'));
  15. }

The contain() method tells the ArticlesTable object to also populate the Tagsassociation when the article is loaded. Now when tag_string is called for anArticle entity, there will be data present to create the string!

Next we’ll be adding authentication.