CakePHP

Hire the Top 3% of Freelance CakePHP Developers

Toptal is a marketplace for top CakePHP developers, engineers, programmers, coders, architects, and consultants. Top companies and start-ups choose Toptal CakePHP freelancers for their mission-critical software projects.

No-Risk Trial, Pay Only If Satisfied.

Clients Rate Toptal CakePHP Developers4.2 / 5.0on average across 37 reviews as of May 2020

Hire Freelance CakePHP Developers and Engineers

Davit Barbakadze

Freelance CakePHP Developer

GeorgiaToptal Member Since June 19, 2019

Over the span of 12+ years, Davit managed to acquire experience in all positions across the stack. Starting as an actual DevOps administrator, writing scripts in Perl, bash, and some PHP back in 2007, he slowly but surely moved towards full-stack web development. Intensively writing IT articles on the way and occasionally teaching, he finally reached his current full-time occupation in all things JavaScript, Node.js, and React.

Show More

Virendra Kumar Sharma

Freelance CakePHP Developer

IndiaToptal Member Since November 23, 2017

Virendra has been working as a developer for nearly a decade now so he’s well versed in utilizing a variety of technologies like PHP, MySQL, HTML, and other open sources built with PHP like Magento, WordPress, OpenCart, CI, and CakePHP. He’s a Magento certified developer along with being a seasoned freelance developer who’s passionate about his work.

Show More

Agnis Āriņš

Freelance CakePHP Developer

LatviaToptal Member Since January 30, 2019

Agnis is an experienced software engineer with a demonstrated history of working in both the academic and industry sectors. He's an expert problem solver specializing in algorithms and mathematics. Agnis joined Toptal to share those skills on projects that involve complex and challenging tasks.

Show More

Michał Krakiewicz

Freelance CakePHP Developer

PolandToptal Member Since January 12, 2017

Michał is a PHP developer with five years of experience and a bachelor's degree in computer science. Currently, he mainly develops with PHP and JavaScript, but he's also a great all-around developer, possessing the ability to work both on the back end and front end. Overall, Michał is a polite, industrious worker who is looking to work on freelance projects that perk his interest.

Show More

Jason Funk

Freelance CakePHP Developer

TurkeyToptal Member Since June 12, 2015

Jason is an experienced web developer with a broad range of both professional and personal technical achievements. He is the founder of Tough Space Consulting, a cloud-based business software consulting company that has helped a number of clients become more efficient and save money by improving their internal business processes. Jason is a strong team player yet at the same time enjoys taking on personal challenges.

Show More

Carlos Minatti

Freelance CakePHP Developer

ArgentinaToptal Member Since January 15, 2013

Carlos is fanatic about Internet and communication technologies and finding ways to help people solve daily problems. He has a host of experience building web and Android applications, and always aims to deliver the best possible user experience.

Show More

Andu Fratu

Freelance CakePHP Developer

SpainToptal Member Since October 30, 2018

Since 2007, Andu has been making a living as a programmer as both a freelancer and as part of various teams for companies big and small. One constant throughout is that he always strives for excellence and to outdo himself on his next project. He also has experience with both web and mobile technologies and is always up for a challenge. Andu is very accustomed to working in diverse environments with people from all over the world.

Show More

Ahmet Unal

Freelance CakePHP Developer

TurkeyToptal Member Since April 4, 2014

A PHP/MySQL developer with more than 10 years of experience in both developing and leading teams, Ahmet is both a problem solver and an architect. He is very experienced with front-end (HTML, jQuery, and CSS) and large-scale websites, music/video streaming apps, and social media apps.

Show More

Chady Kassouf

Freelance CakePHP Developer

CanadaToptal Member Since August 29, 2016

Chady is a full-stack web and iOS developer. He is fully fluent in Objective-C and Swift, and has a very long record of shipping products with the LAMP stack. He has solid experience with all things front-end and can work very closely with designers and UX teams.

Show More

Martin Hein

Freelance CakePHP Developer

ArgentinaToptal Member Since August 28, 2016

Martin is a web developer who specializes in the development of WordPress websites. He has extensive front-end knowledge enabling him to build pixel-perfect templates for the platform. He also is an experienced PHP developer with a broad knowledge of the WordPress environment and likes to build elegant and clean plugins. Martin possesses an analytical mind and has a good sense of design and communication.

Show More

Bartosz Wilczynski

Freelance CakePHP Developer

PolandToptal Member Since June 21, 2018

Since 2011, Bartosz has been working as a Java full-stack web developer—developing products for a software house, building in-house company products, and as a freelancer. He’s worked in Agile teams with daily standups (scrum), CI/CD pipelines, TDD, and scalable architectures. Bartosz is the type of developer who consistently incorporates up-to-date technologies and truly enjoys learning new things.

Show More

Sign up now to see more profiles.

Start Hiring

A Hiring Guide

Guide to Hiring a Great CakePHP Developer

Fully mastering CakePHP can take some time, which makes finding true CakePHP experts a real challenge. The questions presented in this guide can be highly effective in evaluating the breadth and depth of a developer's knowledge of the CakePHP framework.

Read Hiring Guide

CakePHP Hiring Resources

More Resources to Hire CakePHP Developers

Job Description Template

Interview Questions

Common Mistakes

Trustpilot
Toptal in the press

... allows corporations to quickly assemble teams that have the right skills for specific projects.

Despite accelerating demand for coders, Toptal prides itself on almost Ivy League-level vetting.

Our clients
Building a cross-platform app to be used worldwide
Thierry Jakicevic
Building a cross-platform app to be used worldwide
1
2
3
Creating an app for the game
Conor Kenney
Creating an app for the game
1
2
3
Leading a digital transformation
Elmar Platzer
Leading a digital transformation
1
2
3
Testimonials

Tripcents wouldn't exist without Toptal. Toptal Projects enabled us to rapidly develop our foundation with a product manager, lead developer, and senior designer. In just over 60 days we went from concept to Alpha. The speed, knowledge, expertise, and flexibility is second to none. The Toptal team were as part of tripcents as any in-house team member of tripcents. They contributed and took ownership of the development just like everyone else. We will continue to use Toptal. As a start up, they are our secret weapon.

Brantley Pace, CEO & Co-Founder

Tripcents

In addition to sharp technical skills, Faruk had a great attitude and is a really exceptional communicator. He always let us know where he was with his work, thoroughly and reliably. That's not always the case, and it made working remotely considerably easier. He was an easy integration into the team.

Leif Abraham, Co-Founder

AND CO Ventures Inc

I am more than pleased with our experience with Toptal. The professional I got to work with was on the phone with me within a couple of hours. I knew after discussing my project with him that he was the candidate I wanted. I hired him immediately and he wasted no time in getting to my project, even going the extra mile by adding some great design elements that enhanced our overall look.

Paul Fenley, Director

K Dunn & Associates

The developers I was paired with were incredible -- smart, driven, and responsive. It used to be hard to find quality engineers and consultants. Now it isn't.

Ryan Rockefeller, CEO

Radeeus

Toptal understood our project needs immediately. We were matched with an exceptional freelancer from Argentina who, from Day 1, immersed himself in our industry, blended seamlessly with our team, understood our vision, and produced top-notch results. Toptal makes connecting with superior developers and programmers very easy.

Jason Kulik, Co-Founder

ProHatch

As a small company with limited resources we can't afford to make expensive mistakes. Toptal provided us with an experienced programmer who was able to hit the ground running and begin contributing immediately. It has been a great experience and one we'd repeat again in a heartbeat.

Stuart Pocknee , Principal

Site Specific Software Solutions

We used Toptal to hire a developer with extensive Amazon Web Services experience. We interviewed four candidates, one of which turned out to be a great fit for our requirements. The process was quick and effective.

Abner Guzmán Rivera, CTO and Chief Scientist

Photo Kharma

Sergio was an awesome developer to work with. Top notch, responsive, and got the work done efficiently.

Dennis Baldwin, Chief Technologist and Co-Founder

PriceBlink

Working with Marcin is a joy. He is competent, professional, flexible, and extremely quick to understand what is required and how to implement it.

André Fischer, CTO

POSTIFY

We needed a expert engineer who could start on our project immediately. Simanas exceeded our expectations with his work. Not having to interview and chase down an expert developer was an excellent time-saver and made everyone feel more comfortable with our choice to switch platforms to utilize a more robust language. Toptal made the process easy and convenient. Toptal is now the first place we look for expert-level help.

Derek Minor, Senior VP of Web Development

Networld Media Group

Toptal's developers and architects have been both very professional and easy to work with. The solution they produced was fairly priced and top quality, reducing our time to launch. Thanks again, Toptal.

Jeremy Wessels, CEO

Kognosi

We had a great experience with Toptal. They paired us with the perfect developer for our application and made the process very easy. It was also easy to extend beyond the initial time frame, and we were able to keep the same contractor throughout our project. We definitely recommend Toptal for finding high quality talent quickly and seamlessly.

Ryan Morrissey, CTO

Applied Business Technologies, LLC

I'm incredibly impressed with Toptal. Our developer communicates with me every day, and is a very powerful coder. He's a true professional and his work is just excellent. 5 stars for Toptal.

Pietro Casoar, CEO

Ronin Play Pty Ltd

Working with Toptal has been a great experience. Prior to using them, I had spent quite some time interviewing other freelancers and wasn't finding what I needed. After engaging with Toptal, they matched me up with the perfect developer in a matter of days. The developer I'm working with not only delivers quality code, but he also makes suggestions on things that I hadn't thought of. It's clear to me that Amaury knows what he is doing. Highly recommended!

George Cheng, CEO

Bulavard, Inc.

As a Toptal qualified front-end developer, I also run my own consulting practice. When clients come to me for help filling key roles on their team, Toptal is the only place I feel comfortable recommending. Toptal's entire candidate pool is the best of the best. Toptal is the best value for money I've found in nearly half a decade of professional online work.

Ethan Brooks, CTO

Langlotz Patent & Trademark Works, Inc.

In Higgle's early days, we needed the best-in-class developers, at affordable rates, in a timely fashion. Toptal delivered!

Lara Aldag, CEO

Higgle

Toptal makes finding a candidate extremely easy and gives you peace-of-mind that they have the skills to deliver. I would definitely recommend their services to anyone looking for highly-skilled developers.

Michael Gluckman, Data Manager

Mxit

Toptal’s ability to rapidly match our project with the best developers was just superb. The developers have become part of our team, and I’m amazed at the level of professional commitment each of them has demonstrated. For those looking to work remotely with the best engineers, look no further than Toptal.

Laurent Alis, Founder

Livepress

Toptal makes finding qualified engineers a breeze. We needed an experienced ASP.NET MVC architect to guide the development of our start-up app, and Toptal had three great candidates for us in less than a week. After making our selection, the engineer was online immediately and hit the ground running. It was so much faster and easier than having to discover and vet candidates ourselves.

Jeff Kelly, Co-Founder

Concerted Solutions

We needed some short-term work in Scala, and Toptal found us a great developer within 24 hours. This simply would not have been possible via any other platform.

Franco Arda, Co-Founder

WhatAdsWork.com

How to Hire CakePHP Developers through Toptal

1

Talk to One of Our Industry Experts

A Toptal director of engineering will work you to understand your goals, technical needs, and team dynamics.
2

Work With Hand-Selected Talent

Within days, we'll introduce you to the right CakePHP developer for your project. Average time to match is under 24 hours.
3

The Right Fit, Guaranteed

Work with your new CakePHP developer for a trial period (pay only if satisfied), ensuring they're the right fit before starting the engagement.

FAQs

  • How are Toptal CakePHP developers different?

    At Toptal, we thoroughly screen our CakePHP developers to ensure we only match you with talent of the highest caliber. Of the more than 100,000 people who apply to join the Toptal network each year, fewer than 3% make the cut. You'll work with engineering experts (never generalized recruiters or HR reps) to understand your goals, technical needs, and team dynamics. The end result: expert vetted talent from our network, custom matched to fit your business needs. Start now.

  • Can I hire CakePHP developers in less than 48 hours through Toptal?

    Depending on availability and how fast you can progress, you could start working with a CakePHP developer within 48 hours of signing up. Start now.

  • What is the no-risk trial period for Toptal CakePHP developers?

    We make sure that each engagement between you and your CakePHP developer begins with a trial period of up to two weeks. This means that you have time to confirm the engagement will be successful. If you're completely satisfied with the results, we'll bill you for the time and continue the engagement for as long as you'd like. If you're not completely satisfied, you won't be billed. From there, we can either part ways, or we can provide you with another expert who may be a better fit and with whom we will begin a second, no-risk trial. Start now.

1.1KShares
CakePHP

How to Hire a Great CakePHP Developer

CakePHP is an extensive framework whose feature set for web application development has continued to grow substantially since its initial release in 2005. As a result, fully mastering its capabilitiesf or software development can take some time, which makes finding true CakePHP experts a real challenge.

Finding high-quality CakePHP programmers requires a highly-effective recruiting process, as described in our post on Finding and Hiring the Best in the Industry. Such a process can then be augmented with questions – such as those presented herein – to identify those candidates who have truly mastered CakePHP web development.

Q: How do CakePHP conventions and Object-Relational Mapping (ORM) help streamline queries? Also discuss any potential pitfalls.

CakePHP’s Object-relational mapping (ORM) benefits greatly from CakePHP conventions. By setting out the database schema to Cake’s standards, you can quickly connect tables together through Cake’s powerful ORM. You rarely need to write an SQL statement, as CakePHP handles things like table joins, hasMany, and even hasAndBelongsToMany relationships with ease.

Leveraging CakePHP’s ContainableBehavior, through your model associations you can specify which database tables and fields to select from an SQL query. This can go several tables deep, and through the ORM it is easy to rapidly construct highly complex SQL statements. It helps you search and filter data in a clean and consistent way and can also help increase the speed and overall performance of your application. (It works by temporarily or permanently altering the associations of your models, using the supplied containments to generate a corresponding series of bindModel and unbindModel calls.)

Overall, Cake’s ORM really does help streamline development and, if used correctly, is an amazing tool for building complex queries quickly. It is nonetheless vital that developers take the time to fully understand the ORM and to ensure that their queries are are properly optimized (as is true in any language).

The challenge with the ORM is that it makes using SQL so simple that, if a developer isn’t careful, he or she can write inefficient SQL queries without meaning to. These problems tend to surface after a system has been deployed, as databases grow and badly written queries become increasingly slow.

Q: What are CakePHP Helpers? List the 10 types of Helpers that are available and, using the FormHelper as an example, describe how Helpers can be used to speed up development.

CakePHP Helpers are component-like classes for the presentation layer of your application. They contain logic that can be shared by many views, elements, or layouts.

The 10 types of helpers available in CakePHP are:

  1. CacheHelper
  2. FormHelper
  3. HtmlHelper
  4. JsHelper
  5. NumberHelper
  6. Paginator
  7. RSS
  8. SessionHelper
  9. TextHelper
  10. TimeHelper

By encapsulating commonly used functionality in reusable form, CakePHP Helpers help speed up development. A great example is the FormHelper, which creates your form input fields based on your database table schema set up. For example, a TINY INT field will automatically be mapped to a checkbox, while a TEXT field will automatically be mapped to a text area.

By ensuring that the FormHelper names match the same names as in the database table, the form will automatically be created.

Using your data validation rules, CakePHP will automatically display error messages next to the form input if the data validation fails. All that is required is for the developer to match the form input to the fields in the database. With a little bit of help from the controller, the data will then automatically be saved to the database once the validation has passed successfully.

Q: What are Components and what are the benefits of using them? Provide an example of how you would access a component via a controller.

Components are logical modules that are shared between controllers. CakePHP comes with its own set of core components for common tasks and you can also create your own components. Creating and using components can help keep controller code clean and facilitates code reuse across and between projects. For example, you might want to create a custom “shopping cart” component for use across multiple controllers in an e-commerce application.

Each component you include in a controller is exposed as a property on that controller. For example, if you included the SessionComponent and the CookieComponent in your controller, you could access them as follows:

class PostsController extends AppController {
    public $components = array('Session', 'Cookie');

    public function delete() {
        if ($this->Post->delete($this->request->data('Post.id')) {
            $this->Session->setFlash('Post deleted.');
            return $this->redirect(array('action' => 'index'));
        }
    }

Q: What are Behaviors and what are their advantages? List the 4 Behaviors supported “out of the box” in CakePHP.

In much the same way that a Component extends a Controller, a Behavior extends a Model. Behaviors enable you to separate and reuse logic that performs a type of behavior, and to do so without requiring inheritance.

As an example, consider a model that provides access to a database table which stores structural information about a tree. Removing, adding, and migrating nodes in the tree is not as simple as deleting, inserting, and editing rows in the table. Rather than creating those tree-manipulation methods on a per model basis (for every model that needs that functionality), we could simply attach the TreeBehavior to our model.

The following 4 Behaviors are provided “out of the box” in CakePHP:

  1. AclBehavior: provides a way to seamlessly integrate a model with your ACL (Access Control List) system
  2. ContainableBehavior: streamlines search and filter operations
  3. TranslateBehavior: for internationalization
  4. TreeBehavior: facilitates accessing and manipulating hierarchical data in database tables

You can also create your own behaviors. Behaviors can be a great way to keep a clean code base and keep your code out of your controller. A good example is the open source ImageUploadBehavior which allows for a very simple image or file uploading. By specifying a few rules in your model file, files will be automatically validated and uploaded, with no extra code required in your Controller file. An added plus of that particular behavior is that it uses PHP Thumb to automatically resize any image uploads.

Q: How would you handle nested data in CakePHP, such as a category tree?

Creating a category structure which goes unlimited levels deep is a good example of where the CakePHP’s TreeBehavior can come in handy.

Employing the TreeBehavior is trivially simple and is done as follows in your model file:

public $actsAs = 'Tree';

The categories table might then look something like this:

CREATE TABLE categories (
    id INTEGER(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    parent_id INTEGER(10) DEFAULT NULL,
    lft INTEGER(10) DEFAULT NULL,
    rght INTEGER(10) DEFAULT NULL,
    name VARCHAR(255) DEFAULT '',
    PRIMARY KEY  (id)
);

By setting the parent_id field when you save the data, the lft and rght fields will automatically be populated. The lft and rght fields follow an MPTT (Modified Preorder Tree Traversal) structure.

All of the TreeBehavior’s methods are then available for use. Examples include:

  • generateTreeList() - returns a hierarchical array of values (e.g., for use with HTML select boxes, etc.)
  • children($parentId) - returns a list of the children of the specified $parentId
  • getPath($id) - returns an array of the nodes to traverse hierarchically within the tree to reach the specified $id

Q: How do you perform data validation in CakePHP?

CakePHP simplifies data validation, enabling you to specify in your model file the data validation rules for each of your database tables that are universal for that model. This adheres to the DRY (Don’t Repeat Yourself) principle by enabling you to just specify the rules once and then have them apply across the entire model.

The supported validation rules are plentiful in CakePHP. Here are a few good examples:

public $validate = array(
	'phone' => array(
		'rule' => 'phone',
		'message' => 'A valid phone number is required.'
	),
	'email' => array(
		'rule' => 'email',
		'message' => 'A valid email address is required.'
	),
	'password' => array(
		'rule'    => array('minLength', '8'),
		'message' => 'Minimum 8 characters long'
	),
	'dob' => array(
		'rule'    => 'date',
		'message' => 'Enter a valid date',
		'allowEmpty' => true
	)
);

Note in particular the allowEmpty key in the 'dob' array which allows the field to be empty. Based on these validation rules, the dob field can be left blank, but if a date is entered, it will be checked to confirm that it is a valid date value.

Q: Provide some examples of folder and file manipulation in CakePHP.

Often challenging with standard PHP alone, the Folder & File Utilities are useful if you need to create, upload, or manipulate folders or files.

Here are some key examples:

The Folder::copy method simplifies copying a file from one location to another:

// Copy folder1 and all its contents into folder2
$folder1 = new Folder('/path/to/folder1');
$folder1->copy('/path/to/folder2');

The Folder::copy method supports additional options as well. Specifically:

$folder = new Folder('/path/to/folder');
$folder->copy(array(
    'to' => '/path/to/new/folder',
    'from' => '/path/to/copy/from',
    'mode' => 0755,
    'skip' => array('skip-me.php', '.git'),
    'scheme' => Folder::SKIP  // Skip directories/files that already exist
));

Or to create new folders, simply use the Folder::create method:

$folder = new Folder();
if ($folder->create('foo' . DS . 'bar' . DS . 'baz' . DS . 'shoe' . DS . 'horn')) {
    // Successfully created the nested folders
}

The Folder::find method is particularly useful as it enables you to dynamically find files within a directory:

// Find all .png in your app/webroot/img/ folder and sort the results
$dir = new Folder(WWW_ROOT . 'img');
$files = $dir->find('.*\.png', true);

Q: What are some advantages of the “Fat Model, Skinny Controller” approach? Provide an example of how you would use it in CakePHP.

“Fat Model, Skinny Controller” - often advocated by Ruby on Rails developers - is an approach within the Model/View/Controller (MVC) architectural paradigm whereby logic should predominantly exist within the model. This relegates the “skinny” controller to its intended role as a controlling interface between the view and model.

Consider, for example, performing a simple CRUD (create, read, update and delete) operation, such as adding posts to a blog. The default add method might be as follows:

public function add() {
    if ($this->request->is('post')) {
        $this->Post->create();
        if ($this->Post->save($this->request->data)) {
            $this->Session->setFlash(__('Your post has been saved.'));
            return $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Unable to add your post.'));
    }
}

This controller action is fine for a simple add, but what would happen if you wanted to do things such as send an email to the admin when a post was added, or update another model association when a post was added? This is additional logic, but this logic shouldn’t go in the controller file.

Instead we would write a method for this in our Post.php model, perhaps something like this:

public function addPost($data = array(), $emailAdmin = true) {
    $this->create();
    $this->save($data);

    // update any other tables

    if ($emailAdmin) {
    	// send the email to the admin user
    }
 
    // if all is successful
    return true;
}

This would then only require a small change to the controller action as follows:

public function add() {
    if ($this->request->is('post')) {
        if ($this->Post->addPost($this->request->data)) {
            $this->Session->setFlash(__('Your post has been saved.'));
            return $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Unable to add your post.'));
    }
}

As you can see, the new action is actually one less line, because the $this->Post->create() has been moved to the model file, helping achieve clean and concise code.

Q: How does CakePHP handle authentication and user login? Provide a code example.

CakePHP has a built in authentication component (AuthComponent) that makes setting up a user registration and login system very straightforward. By setting up a users table with a username or email field and a password field, a programmer can quickly incorporate authentication into their application. CakePHP also handles password encryption, providing several different classes for encryption including B crypt and digest authentication. CakePHP also has some advanced methods for doing things such as logging users in automatically.

Here’s how you can easily take advantage of these capabilities in your code:

Your database table might look something like this:

CREATE TABLE users (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50),
    password VARCHAR(255),
    role VARCHAR(20),
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL
);

In your AppController.php you would then setup the component:

// app/Controller/AppController.php
class AppController extends Controller {

    public $components = array(
        'Session',
        'Auth' => array(
            'loginRedirect' => array(
                'controller' => 'posts',
                'action' => 'index'
            ),
            'logoutRedirect' => array(
                'controller' => 'pages',
                'action' => 'display',
                'home'
            ),
            'authenticate' => array(
                'Form' => array(
                    'passwordHasher' => 'Blowfish'
                )
            )
        )
    );

In your User.php model file, you would set the password encryption code in the beforeSave callback:

// app/Model/User.php

App::uses('AppModel', 'Model');
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');

class User extends AppModel {

// ...

public function beforeSave($options = array()) {
    if (isset($this->data[$this->alias]['password'])) {
        $passwordHasher = new BlowfishPasswordHasher();
        $this->data[$this->alias]['password'] = $passwordHasher->hash(
            $this->data[$this->alias]['password']
        );
    }
    return true;
}

Then, in your UsersController.php, you can set the login action:

// app/Controller/UsersController.php

public function login() {
    if ($this->request->is('post')) {
        if ($this->Auth->login()) {
            return $this->redirect($this->Auth->redirect());
        }
        $this->Session->setFlash(__('Invalid username or password, try again'));
    }
}

Note how simple it is. The code simply looks for a post, and then calls the Auth->login component method which logs the user in.

The view login file might then look something like this:

//app/View/Users/login.ctp

<div class="users form">
<?php echo $this->Form->create('User'); ?>
    <fieldset>
        <legend>
            <?php echo __('Please enter your username and password'); ?>
        </legend>
        <?php echo $this->Form->input('username');
        echo $this->Form->input('password');
    ?>
    </fieldset>
<?php echo $this->Form->end(__('Login')); ?>
</div>

Just set the form with the username and password fields, and CakePHP handles the rest.

Finally, for the logout script, in your UsersController the logout action could look something like this:

public function logout() {
    return $this->redirect($this->Auth->logout());
}

Q: Provide an example of how you would use CakePHP’s callbacks.

CakePHP callbacks enable you to manipulate or check data before a model operation. Examples include before validation, before save, after save, before delete, after delete, and after find.

For example, consider a case where you want to manipulate a date so that it is displayed differently than the way it is saved in the database. (Perhaps you are working with an older database that saved the date in a time() format or in a non standard database date format.)

To accomplish this, these callbacks could go in your model file:

public function afterFind($results, $primary = false) {
    foreach ($results as $key => $val) {
        if (isset($val['Event']['begindate'])) {
            $results[$key]['Event']['begindate'] = $this->dateFormatAfterFind(
                $val['Event']['begindate']
            );
        }
    }
    return $results;
}

public function dateFormatAfterFind($dateString) {
    return date('d-m-Y', strtotime($dateString));
}

The afterFind callback will take the data returned from a find query, and change the format of the date. In this example, we set the date to be in the d-m-Y format – perhaps preparing the data for going into a date picker or something similar. This code will be called before the data is returned to the controller, so it allows us to manipulate data before we receive it in our controller.

We would also need to have a callback before we save the data, to revert the date format back to that used in the database:

public function beforeSave($options = array()) {
    if (!empty($this->data['Event']['begindate'])) {
        $this->data['Event']['begindate'] = $this->dateFormatBeforeSave(
            $this->data['Event']['begindate']
        );
    }
	// Be sure to return true, or your save is going to fail!
    return true;
}

public function dateFormatBeforeSave($dateString) {
    return date('Y-m-d', strtotime($dateString));
}

Q: What are Virtual Fields in CakePHP? How and why would you use them. Provide an example.

Virtual Fields allow you to create arbitrary SQL expressions and assign them as fields in a model. These fields cannot be saved, but will be treated like other model fields for read operations. They will be indexed under the model’s key alongside other model fields.

As a simple example, consider a model that contains first_name and last_name fields. You might find that you often want to use the user’s full name. In this case, in your model file you can add:

public $virtualFields = array(
    'full_name' => 'CONCAT(User.first_name, " ", User.last_name)'
);

This will add a new field called full_name. When doing a find query, the data would then show as follows:

Array
(
    [0] => Array
        (
            [User] => Array
                (
                    [id] => 1
                    [fist_name] => John
                    [last_name] => Smith
                    [full_name] => John Smith
                )
        )
)

Another good use of virtual fields is when you need to count data. Let’s take the example when an article has comments. Often we need to count how many comments an article has. This is simple to do with virtual fields. For example, in your model file, you could add the following:

public $virtualFields = array(
	'num_comments' => 'SELECT COUNT(id) FROM comments WHERE article_id = Article.id'
);

This will add num_comments at the end of any Article find query, e.g:

Array
(
    [0] => Array
        (
            [Article] => Array
                (
                    [id] => 1
                    [title] => Test Article
                    [description] => Test Description
                    [num_comments] => 2
                )
        )
)

Virtual fields do not come without any penalty though. Their downside is performance. This should be kept in mind when creating virtual fields, as the more complex your virtual field, the more impact on query performance the virtual field will have.

Wrap-up

Whether you are in the United States or aboard, looking for full-time help or part-time help, the questions presented in this guide can be highly effective in evaluating the breadth and depth of a developer’s knowledge of the CakePHP development framework. It is important to bear in mind, though, that these questions are intended merely as a guide. Not every “A” candidate worth hiring will be able to properly answer them all, nor does answering them all guarantee an “A” candidate. At the end of the day, hiring dedicated CakePHP developers remains as much of an art as it does a science.

Featured Toptal CakePHP Publications

Top CakePHP Developers are in High Demand.

Start Hiring
By continuing to use this site you agree to our Cookie Policy.