CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

Using the CakeDC Tags plugin for CakePHP

This is an introduction to using the CakeDC Tags plugin for CakePHP. I'll take you through a new project creation, and the addition of the Tags plugin to your project for use with tagging a Blog model on your project. You should be able to take the skills learnt here to any other project, and start taking advantage of the Tags plugin for tagging your models appropriately.

Lets get started by baking a new project:

cake bake project blog1

Follow the prompts to complete the baking operation.

You will now have a "blog1" directory available. Change into that directory:

cd blog1

ensure that the `tmp` directory is writable:

chmod -R 777 tmp

Open up the `config/database.php.default` file in your favourite editor. Immediately choose to "Save as..." and save the file in the same location omitting the ".default" part of the filename. So save the file as `config/database.php`.

Configure the options at the bottom to match the database credentials for your application. Mine are as follows:

<?php
class DATABASE_CONFIG {
   var $default = array(
      'driver' => 'mysql',
      'persistent' => false,
      'host' => 'localhost',
      'login' => 'dev',
      'password' => 'dev',
      'database' => 'blog1',
      'prefix' => '',
   );
}

For the moment, I have remove the 'test' datasource, as we won't use that right now.

Go ahead and create your MySQL database, and a simple table to hold blog items:

CREATE DATABASE `blog1`;
USE `blog1`;

CREATE TABLE `blogs` (
   `id` CHAR(36) NOT NULL PRIMARY KEY,
   `title` VARCHAR(255) NOT NULL,
   `body` TEXT,
   `created` DATETIME,
   `modified` DATETIME
);

Now lets bake the controller, model and views for this blogs table, in order to be able to add and edit content. Once this is complete, we'll begin integrating the tags plugin into the application.

First bake the model:

cake bake model blog

Next bake the controller. The following bakes all the "public" actions for this controller:

cake bake controller blog public

And finally, the views:

cake bake view all

Browse around your application at the address: /blogs to begin with to ensure that your app is functioning correctly. You should be able to add, edit, delete and view blog entries.

Time to get cracking on the Tags plugin. Our objective here is to tag each blog entry with an arbitrary tag at add / edit time to allow us to easily categorise content we are posting.

In order to download and install the Tags plugin, I'll be using git. You can however download an archive from the github website, and extract that archive into your `APP/plugins` directory. In either case, the result will be a `tags` directory in your `APP/plugins` directory, containing the contents of the CakeDC tags plugin.

From your `APP` directory (in this example, the APP directory is `blog1`), clone the tags repository:

git clone git://github.com/CakeDC/tags.git plugins/tags

The first thing that we need to do now that the Tags plugin has been added to our project, is to create the tables required to store the tag information. These are available in schema's and migrations within the Tags plugin, so you don't need to handle the SQL yourself, just use the cake console to create the tables for you:

If you prefer using the builtin CakePHP schema mechanism, or you are not sure what the "migrations" plugin is, you can create the database tables like this:

cake schema create schema -plugin tags -name tags

If however, you are familiar with using the migrations plugin, or you want to use the migrations plugin for this project, add the migration plugin to your project, and then run the migrations:

git clone git://github.com/CakeDC/migrations.git plugins/migrations

cake migration -plugin tags all

Either method is fine.

Next up, we need to add the `Taggable` behavior from the `Tags` plugin to our model to enable all the awesome functionality. Add the following variable to your `Blog` model in `APP/models/blog.php`:

public $actsAs = array(
   'Tags.Taggable'
);

Finally, we need to add a new input for the tags on our add and edit screens, to allow users to customise the tags they want for the blog posts. Simply add a new input called 'tags' to your forms, such as the following:

echo $this->Form->input('tags', array('type' => 'text'));

Note that this needs to be done for both your add and edit views.

You can also make this be of type `textarea`, if you need gigantic amounts of tags. `text` is fine though, to allow a good number of tags, and to minimise the input space.

This is all you need to do to enable your content to be tagged! Looking back at all the instructions so far, the bulk of the content has been on how to create a new project, bake the model, views and controller, and the addition of plugins. In terms of code addition, we've only added a behavior to the Blog model, and a new input to the add and edit views.

To test your tagging, use a comma to separate your tags when using the tags input. Using a comma allows you to enable users to add multiple-word tags.

What now!? You can tag stuff, thats pretty cool. You probably want to look up blog posts based on tags now. Thats already provided for you in the Tags Controller quick comes with the Tags plugin. Browse to `/tags` to see the tags controller index action from the tags plugin render all the tags that you have added to your blog so far.

There is a whole lot more that you can do with tagging in terms of both operation and the visual representation of the tags themselves. Stay tuned for more blog articles explaining our plugins and other interesting PHP and CakePHP code from myself and the rest of the CakeDC team.

UPDATE: An excellent guide on how to style the tags with CSS has been written by @WyriHaximus, check it out here.

Latest articles

CakePHP API Plugin

Are you creating an API in CakePHP? This task looks very popular these days, and most of our clients need an API to expose certain services to their own rich client applications, or third party services. Even if it's easy to configure CakePHP to expose a REST API, and there are other plugins that could help you building an API, we found ourselves working on specific tweaks per project to adjust the way the API was designed, so we decided to wrap all these ideas and create a specific CakePHP API Plugin including

  • Services definition
  • Integrated CRUD
  • Nested resources
  • Pagination
  • Sorting
  • Associations
  • Versioning
  • Custom Extensions (data format / transformers)
  • Self documentation
We've gathered all the best practices around API building and CakePHP and wrapped them into an easy to install and setup Plugin to be used as the foundation of your API intensive CakePHP projects. Let's walkthru some of the Plugin features using an example application: the bookmarker tutorial http://book.cakephp.org/3.0/en/tutorials-and-examples/bookmarks/intro.html We'll assume you've already created a new CakePHP application and configured it to use the bookmarker database (schema dump here http://book.cakephp.org/3.0/en/tutorials-and-examples/bookmarks/intro.html#creating-the-database).

Setting up the CakePHP API Plugin

Download the plugin first composer require cakedc/cakephp-api:dev-master Then ensure plugin is loaded in you bootstrap.php file Plugin::load('CakeDC/Api', ['bootstrap' => true, 'routes' => true]);

Now you have an API!

Test your newly configured "default" API using curl curl -X GET http://bookmarker.dev/api/bookmarks You'll get something similar to: { "status": "success", "data": [], "pagination": { "page": 1, "limit": 20, "pages": 0, "count": 0 }, "links": [ { "name": "self", "href": "http:\/\/bookmarker.dev\/api\/bookmarks", "rel": "\/api\/bookmarks", "method": "GET" }, { "name": "bookmarks:add", "href": "http:\/\/bookmarker.dev\/api\/bookmarks", "rel": "\/api\/bookmarks", "method": "POST" } ] } If you look at the provided output you'll identify we've used a JSend default renderer (status, data) and we append some extra data under 'links' (HATEOAS dynamically generated for your CRUDs) and pagination. The specific "extensions" used can be configured and custom extensions created for your specific needs, see https://github.com/CakeDC/cakephp-api/blob/master/docs/Documentation/extensions.md We'll publish a couple tutorials soon covering some of the features implemented, and explaining how did we use the CakePHP API Plugin to address specific use cases. Meanwhile, please check the documentation here https://github.com/CakeDC/cakephp-api/blob/master/docs/Documentation/overview.md

Giving back to the community

This Plugin's development has been sponsored by the Cake Development Corporation. Contact us if you are interested in:  

Create Google app for web oauth2 login step by step

Here's a step by step tutorial about how to create a web oauth2 app in Google dashboard.

Google app oauth login app 1
  • Add some cool name for your new Google app project and click "Create"
Google app oauth login app 2
  • Under "Library" section, create a new Google+ API project
Google app oauth login app 3
  • Click "Enable" in the dashboard tab
Google app oauth login app 4
  • Under "Credentials" menu, click "Oauth consent screen" tab and enter some cool name to be displayed to users when requesting their access to your application. Then click "Save".
Google app oauth login app 5
  • Under "Credentials" menu, click "Create credentials" and select "Oauth client ID".
Google app oauth login app 6
  • Now click "Web application" radio, and type your domain name and oauth callback
    • Under "Authorized Javascript origins", add your domain name: mydomain.com
    • Under "Authorized redirect URIs", add all the allowed callback url's to your application. For example if you are using CakeDC/Users Plugin, you'll need to add mydomain.com/auth/google
  • Then click "Save"
Google app oauth login app 7
  • Copy the Iauth client and secret id's into your application configuration
  • Be careful, some browsers will append blank spaces to the codes, remove any extra blank space (trim)
Google app oauth login app 8
  • Ensure the API is enabled, you can test your application now and check there is "Traffic" displayed
  You have now a Google app configured to provide Oauth2 login to your web application. Enjoy!                  

Login with Google Oauth2 in CakePHP using CakeDC/Users Plugin

This article is inspired by this question in Stack Overflow and belongs to a series of articles describing the step by step tutorial to configure CakeDC Users Plugin with the most commonly used Oauth2 providers, in this case we'll configure Google login. We'll assume you have a working CakePHP application with no Auth configured yet.

Setup

Use composer to install the CakeDC Users Plugin and the required oauth2 providers To be able to configure the callbacks in Google dashboard, you'll need to create a virtual host for you application. You don't need a working domain name, you could use something like "mydomain.dev" but Google requires a domain name (no localhost). composer require cakedc/users:@stable composer require league/oauth2-google:@stable Load it from your bootstrap.php file Plugin::load('CakeDC/Users', ['routes' => true, 'bootstrap' => true]); Run migrations to add 2 new tables: 'users' and 'social_accounts' bin/cake migrations migrate -p CakeDC/Users

Configuration

Load the Component in your src/Controller/AppController.php public function initialize() { parent::initialize(); // // ... // $this->loadComponent('CakeDC/Users.UsersAuth'); }

Create a new Google application

<?php // /config/users.php file contents $config = [ 'Users.Social.login' => true, 'OAuth.providers.google.options.clientId' => 'CLIENT_ID_HERE', 'OAuth.providers.google.options.clientSecret' => 'SECRET_HERE', ]; return $config;
  • Modify your bootstrap.php file to ensure the config file is loaded this way
Configure::write('Users.config', ['users']); //add this line before Plugin::load('CakeDC/Users... Plugin::load('CakeDC/Users', ['routes' => true, 'bootstrap' => true]); This file will override any configuration key present in the Plugin, you can check the configuration options here Configuration. Now you are ready to go to your login page and click "Sign up with Google". Upon successful login, a new user will be created in your users table and related oauth2 tokens will be saved in the social_accounts table. The new user created will have the "user" role (by default, but customizable). And based on your Auth rules, this user will be able to access your site. You are done!

Read more about CakeDC Users Plugin

Giving back to the community

This Plugin's development has been sponsored by the Cake Development Corporation. Contact us if you are interested in: We hope you've enjoyed this short tutorial covering the Google login, stay tunned for new CakePHP + Users Plugin tutorials coming soon...

BOOK A 15 MINUTES FREE
CONSULTING WITH US:
We Bake with CakePHP