CakeDC Blog


Create Google app for web oauth2 login...

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:
    • 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
  • 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 us...

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.


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 "" 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


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, '' => 'CLIENT_ID_HERE', '' => '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...

Towards Data Integrity: Validations an...

Let us consider “validation” in a little more detail to see how it has been implemented and optimized in CakePHP 3.0. In addition to what we discussed in the earlier sections, validation now incorporates two complementary conceptions or areas. These include 1) data type and format validation and 2) Application rules. 1. Data Type and Format Validation This part of the validation deals structural aspects such as data type, format validation, and basic types. Unlike in previous versions, validation is applied before ORM entities are created. This is a very useful feature that ensures everything is totally in sync and set in a way that preserves data integrity and the overall stability of the entire application. Moreover, it markedly reduces application errors and inconsistencies throughout the system. It is therefore a significant enhancement over previous versions. 2. Application Rules Application rules are the second component of validation in CakePHP 3.0 implementation. They play a key role in quality control to ensure that all application rules and workflows are operating in an orderly and systematic fashion. This is implemented through buildRules() method in tables. Here is a code example that uses buildRules() method for articles table. // In src/Model/Table/ArticlesTable.php namespace App\Model\Table; use Cake\ORM\Table; use Cake\ORM\RulesChecker; class Articles extends Table {     public function buildRules(RulesChecker $rules)     {         $rules->add($rules->existsIn('user_id', 'Users'));         $rules->add(             function ($article, $options) {                 return ($article->published && empty($article->reviewer));             },             'isReviewed', [                 'errorField' => 'published',                 'message' => 'Articles must be reviewed before publishing.'             ]         );         return $rules;     } } Identifier Quoting Identifier quoting is another CakePHP feature or process that has changed in CakePHP 3.0. In the new release, quoted identifiers, which were expensive and involved a notoriously error-prone process of parsing SQL snippets has been disabled by default - thereby removing a major source of frustration for developers. The only time you may want to enable identifier quoting is when working with column names or table names with special characters or reserved words. Here is how to enable identifier quoting when configuring a connection. // In config/app.php 'Datasources' => [     'default' => [         'className' => 'Cake\Database\Driver\Mysql',         'username' => 'root',         'password' => 'super_secret',         'host' => 'localhost',         'database' => 'cakephp',         'quoteIdentifiers' => true     ] ],
Note: Identifiers in QueryExpression objects require manual quoting or IdentifierExpression objects.   Updating Behaviors Let us now turn to behaviors. As with most features that has to do with ORM, the way behaviors are setup and configured has evolved for smooth integration with the new framework. Among other things, behaviors now attach to table instances. Here are some other significant differences in the way behaviors are handled in CakePHP as compared to earlier versions. 1. Each table that uses a behavior will have its own instance. No storing of “name space” setting in a behavior is required. 2. Method signature for mixin, callback, and base class for behaviors have all changed 3. Finder methods can now be added easily by behaviors.   The above, in a nutshell, summarizes the main changes and enhancements in the new ORM and CakePHP 3.0 in general. Like all major releases or upgrades, the new release supplants many processes and functions in previous versions while at the same time adding many brand new features. But as you go through the initial learning curve, please remember that you, the developer, have been the primary driving force behind the changes and enhancements. Your feedback and critiques over the years was the invaluable source that inspired CakePHP team to produce this groundbreaking and cutting-edge release that you are reviewing.


CakePHP ORM 3.0 Unleashes New, Flexibl...

  In line with its overall goal of eliminating redundancy and increasing efficiency, the new ORM has replaced several functions in the earlier versions with newer and significantly improved functions or functionality. Among the functions affected, we will confine ourselves here to three functions, commands, or processes: 1. afterFind or virtual fields Developers of previous versions will recall how extensively they had to use afterFind callback and virtual fields to generate data properties. In the new CakePHP 3.0, this is no longer necessary and has been removed in favor of virtual properties on entities which are easier and more powerful. For example, using this method, properties can be generated on the fly to user entities with both first and last names by adding an accessor for full_name. Here is a code example. By defining accessors you can provide access to fields/properties that do not actually exist. For example if your users table has first_name and last_name you could create a method for the full name: namespace App\Model\Entity; use Cake\ORM\Entity; class User extends Entity { protected function _getFullName() { return $this->_properties['first_name'] . ' ' . $this->_properties['last_name']; } } You can access virtual fields as if they existed on the entity. The property name will be the lower case and underscored version of the method: echo $user->full_name; Do bear in mind that virtual fields cannot be used in finds. Once a code segment similar to the above has been defined, the new property can be accessed easily using $user->full_name. Moreover, you can build aggregated data sets from your results. Note also that though virtual fields no longer constitute an explicit feature of ORM, you will still be able to achieve the same result using query builder and expression objects which are more powerful and flexible. Here is a code example that will make this clear. 2. Definition of Associations Another extremely important feature introduced in CakePHP 3.0 is the use of methods to create associations. Instead of defining associations using properties like $belongsTo and $hasMany, this significant attribute uses methods that bypass the many inherent limitations of class definitions by allowing only one way of defining associations. Furthermore, the same API handles the “initialize” method and all other parts of your application code when manipulating associations. This is much more efficient and significantly improves productivity. Here is a code snippet to illustrate this. class ArticlesTable extends Table { public function initialize(array $config) { $this->belongsTo('Authors'); $this->hasMany('Comments', [ 'className' => 'Comments', 'conditions' => ['approved' => true] ]); $this->hasMany('UnapprovedComments', [ 'className' => 'Comments', 'conditions' => ['approved' => false], 'propertyName' => 'unapproved_comments' ]); } } Beside the use of methods to create associations as shown in the example above, the awkward name hasAndBelongsToMany has been renamed to belongsToMany. As if the above enhancements were not enough, CakePHP 3.0 has equipped developers with the ability to create custom association classes which will be a welcome relief as a safety valve for situations where the built-in relation types do not meet specific requirements. For more details on creating associations, please consult our section: Associations – Linking Tables together. 3. Validation Rules Validation plays a crucial role in all software development efforts but if they are to contribute to the overall productivity of the development cycle, the way they are defined and used must be straightforward and easy. When it comes to validation rules, CakePHP 3.0 team introduced an elegant solution to many problems with earlier versions through the use of Validator object to generate validation rules. With this feature, defining multiple sets of rules has become a breeze! Here is an example:   class UsersTable extends Table { public function validationPasswordConfirm(Validator $validator) { $validator ->requirePresence('password_confirm', 'create') ->notEmpty('password_confirm'); $validator->add('password', 'custom', [ 'rule' => function ($value, $context) { $confirm = Hash::get($context, 'data.password_confirm'); if (!is_null($confirm) && $value != $confirm) { return false; } return true; }, 'message' => __d('Users', 'Your password does not match your confirm password. Please try again'), 'on' => ['create', 'update'], 'allowEmpty' => false ]); return $validator; } } In Patch entity validationPasswordConfirm will be applied if is passed in ‘validate’ param.   $user = $this->Users->patchEntity($user, $this->request->data(), ['validate' => 'passwordConfirm']); What is noteworthy about the above code segment is the ability to define as many validation methods as needed. Notice how each method should be prefixed with validation and should be structured to accept a $validator argument.

How CakePHP can boost your organizatio...

  As the name suggests, CakePHP is a delightfully easy-to-use framework for rapid application development (RAD). It has evolved to become the most advanced and the most sought-after rapid application development in PHP. Part of this popularity stems from the framework’s ability to simultaneously fulfill the needs of the various stake holders to a project including business owners, project managers, developers, and system administrators. If you are a business owner, you will love CakePHP because it requires no purchasing costs and no licensing fees. Moreover, the entire development cycle from conception to development to deployment is so breathtakingly simple that it can be completed in a matter of weeks. This is possible because CakePHP, from its very inception, was designed to streamline and simplify the process of delivery. The precious time and effort that is often wasted in frantically wrestling with code to make it work can instead be redirected to building a feature-rich site. If you are a project manager, CakePHP is an answer to your projects. You will be relieved to find out that it resolves many issues that pestered you in the past. First, costing less than a fraction of what other commercial products charge, it will neatly fit your business plan whatever the size of your organization. Second, assembling a team of highly qualified developed will be easy due to the abundance of PHP developers. Third, it requires little training or coaching due to its intuitive simplicity and the lots of clear documentation that come with it. And finally, its functionality can be expanded and enhanced to meet the growing demands and needs of a project or an organization. Likewise, if you are a developer, you will find CakePHP markedly boosts your productivity and the quality of the final deliverable you hand over. Furthermore, it obviates the need for the often tedious and prone to error process of integrating different components. With CakePHP, you can have a fully functional unit in half a day or so because code generation tools do much of the work for you. From simple design and syntax to application scaffolding and code generation tools, CakePHP makes it easy for all developers regardless of skill levels to achieve quick results with minimum effort. Even developers with little or no previous web development experience will be able to learn it and figure out its syntax and conventions. Another important feature of CakePHP is its innovative implementation of “convention over configuration” concept that drastically reduces the overall size of code. This is a technique that bypasses endless configuration and setting by attributing special meaning to names given to tables, fields, directories, classes etc… To this end, CakePHP requires adherence to naming conventions. MVC is also another aspect of CakePHP that contributes to its flexibility and robustness. By dividing the system into three distinct self-contained layers according to function, CakePHP ensure the maintainability and manageability of your code. Last but not least, system administrators will appreciate the ease with which CakePHP can be installed on an existence system. A ready-made package, the framework is easy to decipher and configure. Plug-ins and third party libraries are also available for added functionality when and if needed. Additionally, it has a flexible directory structure, solid security infrastructure, and support for the most popular databases. All a system administrator need to do to get the ball rolling is to download the code; define databases, and set file permissions and, voila, the system is ready to go! The above is a brief synopsis of what CakePHP can do for you. Whether what you want is rapid prototyping or the creation of full-fledged website, you will find all the necessary tools within CakePHP. Please contact us if you have questions or need a more detailed explanation of its many features.

We Bake with CakePHP