Utility Open Source Apps In CakePHP That You Need To Know

CakePHP is one of the most popular open source web application framework. It provides an extensible architecture for development, maintenance and deployment of PHP applications. Being based on the MVC Architecture & ORM, it is relatively simple to understand and helps developers to write less code without losing flexibility.

The key features of Open Source Apps written in CakePHP are:

  • Flexible Licensing
  • Works from any Website Directory, with Little Number of Apache Configuration involved
  • Integrated CRUD for Database Interaction
  • Code Generation & Built-in Validation
  • Request Dispatcher with Clean, Custom URLs and Routes
  • Fast and Flexible Templating (PHP Syntax with Helpers)
  • View Helpers for AJAX, JavaScript, HTML Forms and much more
  • Email, Cookie, Security, Session and Request Handling Components
  • Flexible ACL and Data Sanitization
  • Flexible Caching and Localization

CakePHP has the second largest active developer team and community among the PHP frameworks, bringing great value to the project. It keeps you away from reinventing the wheel.

Never miss an update from us. Join 10,000+ marketers and leaders.

Github is the #1 resource for Cakephp projects in my opinion. 2nd place probably is occupied by Code Google and then comes Sourceforge.

Orangescrum

Orangescrum is a flexible project management web application developed using CakePHP framework. It’s an efficient Project Collaboration Tool that gives you full visibility and control over your projects. Orangescrum offers all the basic features you need for smooth running of your project. No matter where you are globally, with Orangescrum you feel like sitting next to your developer. With an intuitive interfaces, easy-to-use functionality, you organize your project activities to a great extent.

Disclaimer: It’s our own project management tool.

https://github.com/Orangescrum/orangescrum

Croogo

Croogo is a free, open source, Multilingual Content management system built using CakePHP MVC framework. It’s an open source project released under MIT License. With Croogo CMS, you can create your own content type such as blog, node, page, etc.  Also you can categorize content with Taxonomy and it also offers WYSIWYG editor to edit content directly from browser.

Zhen CRM

Zhen CRM is a self-hosted CRM with full source code (in CakePHP and MySQL) that aims to be visually easy to use, simple and straightforward, and provides all the features you need from a full-featured CRM!

Vamcart

Vamcart is a CakePHP based open source Shopping cart. It is easy to use and simple to install. It is not required to have any special knowledge to install Vamcart on your server. Just download the files from vamcart homepage and put them on your server’s root directory and open Vamcart installation page directly from the browser. The script will automatically install shopping cart on your site.

QuickApps

QuickApps is a CakePHP based open source Content management system. It is easy to use and simple to install. It allows developers and advanced users to easily build complex websites without reinventing the wheel.

 

Recommended Blog: Containable Behavior in CakePHP

Definitely, this list is incomplete. Share your favorite open source CakePHP application with us in the comments below.

How To Do Custom Pagination In CakePHP

Sometimes we need to do pagination in CakePHP using a traditional SQL query, thereby the CakePHP predefined pagination functionality is lost.

We can implement pagination method in the Model or Behavior when we are using standard SQL query in CakePHP. Just need to make sure that the result cannot be obtained with core model methods, or a custom finder before implementing custom queries pagination.

But we can’t just use the standard pagination on the custom queries, we have to override the paginate functions in model or behavior.

To use our own method/logic to override the CakePHP pagination in the model, we need to add two functions: paginate() and paginateCount().

In these functions, we can implement our own paginate logic.

Overriding paginate() function in CakePHP Post Model:

[php]public function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {
$orderStr = ”;
foreach($order as $k => $ord) {
$orderStr[] = $k . ‘ ‘ . $ord;
}
$orderStr = ‘ORDER BY ‘. implode(‘, ‘, $orderStr);

$qryCond = ‘1’;
if (isset($conditions[‘Post.title LIKE’])) {
$qryCond = ‘title LIKE \”.$conditions[‘Post.title LIKE’].’\”;
}

$qryFlds = ‘*’;
if ($fields) {
$qryFlds = implode(‘, ‘, $fields);
}

$sql = ‘SELECT ‘.$qryFlds.’ FROM posts as Post WHERE ‘.$qryCond.’ ‘.$orderStr . ‘ LIMIT ‘ . (($page-1) * $limit) . ‘, ‘ . $limit;
$results = $this->query($sql);
return $results;
}[/php]

Overriding paginateCount() function in CakePHP Post Model:

[php]public function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
$qryCond = ‘1’;
if (isset($conditions[‘Post.title LIKE’])) {
$qryCond = ‘title LIKE \”.$conditions[‘Post.title LIKE’].’\”;
}

$sql = ‘SELECT COUNT(*) as count FROM posts as Post WHERE ‘.$qryCond;

$this->recursive = -1;

$results = $this->query($sql);
return $results[0][0][‘count’];
}[/php]

Using in the Post Controller: We can adjust the fields to get, column ordering, add certain conditions or adjust row limit per page.

[php]public function index() {
$this->paginate = array(
‘limit’ => 10,
‘fields’ => array(‘Post.id’, ‘Post.title’, ‘Post.created’),
‘conditions’ => array(‘Post.title LIKE’ => ‘%search_keyword%’),
‘order’ => array(‘Post.title’ => ‘asc’, ‘Post.id’ => ‘asc’)
);
try {
$this->set(‘posts’, $this->paginate(‘Post’));
} catch (NotFoundException $e) {
$this->redirect(‘index_custom’);
}
}[/php]

The above example is based on specific model and requirement, need to adjust the methods according to the requirements.

See Also: Creating a custom handler session in CakePHP 2.x

Best of luck and happy pagination.

Hope you liked this. Let me know if you want to add anything?

How To Setup CakePHP DataSource For Solr?

Imagine that you have millions of data and your SQL database is not optimized enough to handle them, then “Solr” is your best data source. Apache Solr is a fast search platform. It’s major features include full-text search faceted search, dynamic clustering, database integration, rich document handling. Solr is highly scalable and it is the most popular enterprise search engine.

This document will guide you through DataSource setup for Solr in CakePHP. Set-up the Solr DataSource in CakePHP and query Solr with your CakePHP model “find” function, just similar to querying any other SQL database.

/app/Config/database.php:

Configuring your the DataSource for Solr database connection:

  • host: Solr server address.
  • port: Solr server port.
  • datasource: This should match with your DataSource at /app/Model/Datasource/SolrSource.php

[php]class DATABASE_CONFIG {
public $solr = array(
‘datasource’ => ‘SolrSource’,
‘host’ => ‘192.168.2.131’,
‘port’ => ‘9983’,
‘path’ => ‘/solr/’
);
}[/php]

/app/Model/Solr.php:

Use the database config in your models like:

[php]class Solr extends AppModel {
 public $useTable = false;
 public $useDbConfig = ‘solr’;
 }[/php]

/app/Model/Datasource/SolrSource.php:

Below code describes only the most required functions.

  • You can find other required functions at http://book.cakephp.org/2.0/en/models/datasources.html
    Like: calculate($model, $func, $params) and others create(), update(), delete().
  • Below DataSource only implements read() function.
  • Create a file called SolrSource.php and use below code:

[php]App::uses(‘HttpSocket’, ‘Network/Http’);
require_once($_SERVER[‘DOCUMENT_ROOT’].’/root_folder/app/Vendor/Apache/Solr/Service.php’);
class SolrSource extends DataSource {

protected $_schema = array();
protected $_host;
protected $_port;

public function __construct($config){
parent::__construct($config);
$this->Http = new HttpSocket();

$this->host = $config[‘host’];
$this->port = $config[‘port’];
$this->_schema = $config[‘path’];

$this->solr=new Apache_Solr_Service($this->host, $this->port, $this->_schema);
}

public function read(Model $model, $queryData = array(), $recursive = null) {
$results = array();
$query = $queryData[‘conditions’][‘solr_query’];
if (Configure::read(‘log_solr_queries’) === true) {
CakeLog::write(‘debug’, $query); /* Logs the solr query in app/tmp/logs/debug.log file */
}

try {
$solr_docs = $this->solr->search($query, $queryData[‘offset’], $queryData[‘limit’], array(‘sort’ => $queryData[‘order’]));
} catch (Exception $e) {
CakeLog::write(‘error’, $e->getMessage()); /* Logs the solr errors message in app/tmp/logs/error.log file */
CakeLog::write(‘error’, $query); /* Logs the solr query in app/tmp/logs/error.log file */
}
$model->params = $solr_docs->responseHeader->params;
$model->numFound = $solr_docs->response->numFound;
$docs = $solr_docs->response->docs;
foreach ($docs as $doc) {
$document = array();
foreach ($doc as $fieldName => $fieldValue) {
$document[$fieldName] = $fieldValue;
}
$results[] = $document;
}
return array($model->alias => $results);
}
}[/php]

/app/Controller/UsersController.php:

Getting data from Solr server by using above SolrSource.

[php]App::uses(‘AppController’, ‘Controller’);
class UsersController extends AppController {

public $name = ‘Users’; //Controller name
public $uses = array(‘Solr’); //Model name

function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow(‘index’);
}

public function index(){
$cond = "active:1";
$sort = "timestamp desc";

$params = array(
‘conditions’ =>array(
‘solr_query’ => $cond
),
‘order’ => $sort,
‘offset’ => 0,
‘limit’ => 1
);

$result = $this->Solr->find(‘all’, $params);
$this->layout = ‘ajax’;
header(‘Content-Type: application/json; charset=utf-8’); /* To send response in json format */
echo json_encode($result);
die;
}
}[/php]

See Also : How to use ‘neighbors’ with ‘find’ method

Debugging:

The above code has been tested and validated with CakePHP 2.2.3, PHP 5.3.1 .
Incase you face any problems:

  • First check the DataSource configuration in /app/Config/database.php.
  • Check /app/Model/Solr.php for this line: public $useDbConfig = ‘solr’;
  • Make sure Solr Service Vendor loaded in /app/Model/Datasource/SolrSource.php.
  • Check the path is correct for the Solr vendor.

Hope you liked this. Let me know if you want to add anything?

Creating A Custom Handler Session In CakePHP 2.x

Sessions manage and customization is very easy in CakePHP. Setting and configuration come out of the box so basically you don’t need to configure at all. But still at some point we need customization like, if we need some changes in php.ini or want to store session in a different place.

You can manage session, write custom handler, add option to save on different places, override php.ini settings.

Write Your Own Custom Handler For Sessions in Cake:

To Save Session With Setting in php.ini:

Configure::write('Session', array(
'defaults' => 'php'
));

This is the default setting that comes out of the box by CakePHP.

To Save Session Inside Cake tmp Folder:

Configure::write('Session', array(
'defaults' => 'cake'
));

This is required in a host where it does not allow you to write outside your home directory.

To Save Session in Database:

Configure::write('Session', array(
'defaults' => 'database'
));

This uses a built-in database defaults. It stores session in ‘cake_sessions’ table.
So you need to create a table for this:

CREATE TABLE `cake_sessions` (
`id` varchar(255) NOT NULL DEFAULT '',
`data` text,
`expires` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);

But you can specify you own session handler to store session using a different model:

Configure::write('Session', array(
'defaults' => 'database',
'handler' => array(
'model' => 'MyCakeSession'
)
));

Create ‘MyCakeSession’ model at app/Model/MyCakeSession.php  And create ‘my_cake_sessions’ table:

CREATE TABLE `my_cake_sessions` (
`id` varchar(255) NOT NULL DEFAULT '',
`data` text,
`expires` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);

This will save session ‘my_cake_sessions’ using MyCakeSession model.

To Save Session in Cake Cache:

Configure::write('Session', array(
'defaults' => 'database'
));

Making Session Persist Across All Sub-Domains:

  • Add below in bootstrap:
    ini_set(‘session.cookie_domain’, env(‘HTTP_BASE’));
  • This changes the default, that only the domain generating a session can access, to all sub-domains.
  • You don’t need to make core Security.level to low or medium.
  • You can also use php, cake, database or cache in core Session default to persist session in all sub-domains.

Troubleshoot:

  • When you test with the session management you might get error: “cakephp 404 The request has been black-holed”.
  • Try clear tmp/cache/, tmp/cache/models, tmp/cache/persistent, tmp/sessions.
  • Try clear browser cookie and cache.
  • Check core Session configurations.

Always try to clear browser cookie, cache before doing changes in core Session or php.ini configuration.

Other Session configuration that can be done are cookie name, timeout, cookieTimeout, checkAgent, autoRegenerate, and other ini values like cookie_secure, cookie_path, cookie_httponly.

See Also : How to migrate CakePHP 1.x to 2.x

Like this blog? I’d love to hear about your thoughts on this. Thanks for sharing your comments.

Containable Behavior in CakePHP

When we are going to retrieve records of (user) using User model, we can get the associated model’s record at the same time. That might not require at some point. To avoid this, CakePHP provides the bindModel/unbindModel methods. But this is not be a good practice. You can streamline your operation using the containable behavior. The performance and the speed will increased as well. It will mostly reduce the joining of tables.

Usage & Examples:

class User extends AppModel {
     public $actsAs = array('Containable');
   }

Where “User” is the model for which you are adding the containable behavior.

You can also do the following on the fly:

$this->User->Behaviors->load(‘Containable’);

Operations:

Without the use of Containable

$this->User->find('all');
  Here User model has hasMany relation with the Comment.
  [0] => Array
        (
            [User] => Array
                (
                    [id] => 1
                    [title] => First article1
                    [content] => aaa1
                    [created] => 2008-05-17 00:00:00
                )
            [Comment] => Array
                ( [0] => Array
          (
            [id] => 1
            [User_id] => 1
            [author] => Daniel1
            [email] => dan@example.com1
            [website] => http://example.com1
            [comment] => First comment1
            [created] => 2008-05-17 00:00:00
          )
        [1] => Array
          (
            [id] => 2
            [User_id] => 1
            [author] => Sam1
            [email] => sam@example.net1
            [website] => http://example.net1
            [comment] => Second comment1
            [created] => 2008-05-10 00:00:00
          )
      )
  )
  [1] => Array
  (
    [User] => Array
      (...

Using Containable:

Case 1: If we need only User data.

$this->User->contain();
      $this->User->find('all');
  OR
  $this->User->find('all', array('contain' => false));
  Out Put:
  [0] => Array
        (
            [User] => Array
                (
                    [id] => 1
                    [title] => First article1
                    [content] => aaa1
                    [created] => 2008-05-17 00:00:00
                )
        )
       [1] => Array
        (
            [User] => Array
                (
                    [id] => 2
                    [title] => Second article1
                    [content] => bbb1
                    [created] => 2008-05-10 00:00:00
                )
        )
  Case 2: With complex associations
       $this->User->contain('Comment.author');
           $this->User->find('all');
 
           // or..
 
           $this->User->find('all', array('contain' => 'Comment.author'));
  Out put:
  [0] => Array
        (
            [User] => Array
                (
                    [id] => 1
                    [title] => First article1
                    [content] => aaa1
                    [created] => 2008-05-17 00:00:00
                )
            [Comment] => Array
                (
                    [0] => Array
                        (
                            [author] => Daniel1
                            [User_id] => 1
                        )
                    [1] => Array
                        (
                            [author] => Sam1
                            [User_id] => 1
                        )
                )
        )
 
   $this->User->find('all', array('contain' => 'Comment.author = "Daniel1"'));
 
    Out put:
  [0] => Array
        (
            [User] => Array
                (
                    [id] => 1
                    [title] => First article1
                    [content] => aaa1
                    [created] => 2008-05-17 00:00:00
                )
            [Comment] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [post_id] => 1
                            [author] => Daniel1
                            [email] => dan@example.com1
                            [website] => http://example.com1
                            [comment] => First comment1
                            [created] => 2008-05-11 00:00:00
                        )
                )
        )
  [1] => Array
        (
            [User] => Array
                (
                    [id] => 2
                    [title] => Second article2
                    [content] => bbb2
                    [created] => 2008-05-22 00:00:00
                )
            [Comment] => Array
                (
                )
        )

The gray area showing that the User data always returned irrespective of the “Comment”.

Pagination Using Containable:

Including the ‘contain’ parameter in the $paginate property we can achieve find(‘count’)
and find(‘all’) on the model. This is a most valuable feature of CakePHP.

$this->paginate['User'] = array(
    'contain' => array('Comment', 'Tag'),
    'order' => 'User.name'
  );
  $users = $this->paginate('User');

If you are searching for PHP or CakePHP developers, then we are the ideal and cost savvy option for you.

Like this blog? I’d love to hear about your thoughts on this. Thanks for sharing your comments.

Download responsive Web Templates for FREE

We at Andolasoft are delighted to release a collection of responsive web templates for free usage. You can download and use them absolutely FREE (We don’t ask for any Credit Card) for your website. These web templates are fully responsive such that even a mobile reader gets best user experience. You can download free templates/themes by visiting following linkshttps://www.andolasoft.com/ebook/

It is true that to create a website you need to have lot of skills and energy. If you are not so good with HTML, CSS or web designing, our website templates will be perfect solution for you. We can provide you the HTML of the template you are interested with.

We’re sure you will find these templates useful regardless if you’re a newbie or a pro webmaster. However, you are free to alter templates to suit your needs and apply to your personal or commercial websites without any restriction.

What are you waiting for? Go and get from the pool:

education1

mobile

 

 

 

 

 

 

 

web_software

You can checkout some of our cool free apps. Feel free to share your opinions in the comments section below: