How To Insert Multiple Rows In CakePHP 3

One of my many issues with CakePHP 2 was lack of multi-row inserts. Cake2 allows saving multiple rows through a single call via saveMany but the issue is with a bunch of single row inserts which can be really slow down when inserting large data; unlike CakePHP 3. Here is what I did to fix this:

[code language=”html”]
$sql = "INSERT INTO `people` (`name`, `title`) VALUES ";
foreach ($people as $person){
list ($name, $title) = $person;
$sql.= "(‘$name’,’$title’),";
}
$this->query (substr ($sql, 0,-1));
[/code]

This sucks since I’m not using any framework and I’m also not using PDO bound parameters.

Cake3 has the fixes with the new Query Builder ORM.

[code language=”html”]
$peopleTable = TableRegistry::get (‘People’);
$oQuery = $peopleTable->query ();
foreach ($people as $person) {
$oQuery->insert ([‘name’,’title’])
->values ($person); // person array contains name and title
}
$oQuery->execute ();
[/code]

The key here is not to issue execute () until after you’ve added all your data via insert (). This will return an instance of the PDO Statement object which inherits all sorts of valuable methods including count () which would give you the total number of rows inserted and errorInfo () for query errors.

Did you find the above tips useful? Feel free to drop in your suggestion…

Please visit Andolasoft’s CakePHP Service to know more.

Quick Steps To Export HTML Content To Doc In CakePHP

Please follow these Simple & Quick Steps to Export your HTML Content to Doc in CakePHP:-

Step#1: Build the <HTML> content dynamically according to the requirement.

Step#2: Store the <HTML>content in a variable (Example: $ExportContent)

[code language=”html”]
$ExportContent = ‘&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
&lt;/head&gt;

&lt;body&gt;

&lt;h2&gt;Mark sheet Table&lt;/h2&gt;

&lt;table style="width:100%" border="1" cellspacing="0"&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;th&gt;Number&lt;/th&gt;
&lt;th&gt;First Name&lt;/th&gt;
&lt;th&gt;Last Name&lt;/th&gt;
&lt;th&gt;Points&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1&lt;/td&gt;
&lt;td&gt;Eve&lt;/td&gt;
&lt;td&gt;Jackson&lt;/td&gt;
&lt;td align="right"&gt;94&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;2&lt;/td&gt;
&lt;td&gt;John&lt;/td&gt;
&lt;td&gt;Doe&lt;/td&gt;
&lt;td align="right"&gt;80&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;

&lt;/body&gt;
&lt;/html&gt;
‘;
[/code]

Step#3: After building the content pass appropriate headers to convert this <HTML>content to Doc

[code language=”html”]
header("Content-type: application/vnd.ms-word");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
[/code]

Step#4: Provide file name to “Content-Disposition” header that we want to give the doc file name

[code language=”html”]
header("Content-Disposition: attachment; Filename=myfile.doc");
echo $ExportContent;
[/code]

Did you find above tips useful? Feel free to drop in your suggestion…

Interested in anything on CakePHP? Let’s have a quick discussion.

Generate Full Working CRUD Skeleton Using CakePHP 2.x Bake Console

CakePHP’s bake console is a command line tool to build fully functional CRUD(Create, Read, Update, Delete) skeleton for your project. As we know CakePHP 3.x is at our doorstep and scaffolding has been removed from it. Cake’s bake console is the extensive scaffolding that generates well documented code for the CRUD operation.

The Cake’s bake console helps you to generate the code for model validations and model relationship. It will ask you, what kind of validation you want and also suggest you the model relationship as per the database convention. We just have to confirm them in command prompt. Going further, Bake can also write Unit Tests for you.

Configurations

       Windows

  1. Set the environment variable in your windows machine. Add this line on your environment path –“;D:\xampp\php\;D:\xampp\htdocs\myproject\app\Console\;”
  2. Open the windows command prompt and go to the path – myproject/app/Console

NOTE: If you you have git bash in windows, you don’t have to set the environment variables. Go to the project folder myproject/app/Console and open git bash.

        Linux

  • No configurations needed, just go to the path – myproject/app/Console in your command line.

CRUD-grid-table-cakePHP

Commands

The bake console commands are very easy. It is well documented and it will walk you through the process while you are generating the code.

cake bake   is the command to start generating CRUD and it will ask, what do you want to bake.

cake bake all – this will generate code for your model, view and controller. But before that, it will ask you to select a model(as per the database table).

Other commands are: cake bake controller, cake bake model, cake bake view, cake bake project

List of Files (Command: cake bake all)

  • It creates your Controller with four actions – index, view, add, edit.
  • The same index, view, add, edit .ctp view files will be created respectively in the view folder.
  • Model file will be created with all the validations and relationships stated by you while generating them on bake console. (If you have an existing Model, it will ask you to overwrite that)

Functionality

Create

  • In the add.ctp file you can find the form and the fields to add a new record.

Read

  • The listing(index.ctp) comes with sorting and pagination.
    The view.ctp is the view details of the record.

Update

  • It is the edit.ctp, file with pre-filled data in the form to edit the record.

 Delete

  • In the listing, you can find the delete link in each records to delete that record.

People say, Cake’s bake is the best friend of “lazy type” developer, but its not true. Smart developer does things quicker and faster with the help of CakePHP’s bake console.

We hope this article would help you to kickstart your CakePHP project real quick. If you have any question or suggestions, you can ask us in the comment section.

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 =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; $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-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;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-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;recursive = -1;

$results = $this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;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-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;paginate = array(
‘limit’ =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; 10,
‘fields’ =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; array(‘Post.id’, ‘Post.title’, ‘Post.created’),
‘conditions’ =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; array(‘Post.title LIKE’ =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; ‘%search_keyword%’),
‘order’ =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; array(‘Post.title’ =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; ‘asc’, ‘Post.id’ =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; ‘asc’)
);
try {
$this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;set(‘posts’, $this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;paginate(‘Post’));
} catch (NotFoundException $e) {
$this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;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’ =&amp;amp;amp;gt; ‘SolrSource’,
‘host’ =&amp;amp;amp;gt; ‘192.168.2.131’,
‘port’ =&amp;amp;amp;gt; ‘9983’,
‘path’ =&amp;amp;amp;gt; ‘/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-&amp;amp;amp;gt;Http = new HttpSocket();

$this-&amp;amp;amp;gt;host = $config[‘host’];
$this-&amp;amp;amp;gt;port = $config[‘port’];
$this-&amp;amp;amp;gt;_schema = $config[‘path’];

$this-&amp;amp;amp;gt;solr=new Apache_Solr_Service($this-&amp;amp;amp;gt;host, $this-&amp;amp;amp;gt;port, $this-&amp;amp;amp;gt;_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-&amp;amp;amp;gt;solr-&amp;amp;amp;gt;search($query, $queryData[‘offset’], $queryData[‘limit’], array(‘sort’ =&amp;amp;amp;gt; $queryData[‘order’]));
} catch (Exception $e) {
CakeLog::write(‘error’, $e-&amp;amp;amp;gt;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-&amp;amp;amp;gt;params = $solr_docs-&amp;amp;amp;gt;responseHeader-&amp;amp;amp;gt;params;
$model-&amp;amp;amp;gt;numFound = $solr_docs-&amp;amp;amp;gt;response-&amp;amp;amp;gt;numFound;
$docs = $solr_docs-&amp;amp;amp;gt;response-&amp;amp;amp;gt;docs;
foreach ($docs as $doc) {
$document = array();
foreach ($doc as $fieldName =&amp;amp;amp;gt; $fieldValue) {
$document[$fieldName] = $fieldValue;
}
$results[] = $document;
}
return array($model-&amp;amp;amp;gt;alias =&amp;amp;amp;gt; $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-&amp;amp;amp;gt;Auth-&amp;amp;amp;gt;allow(‘index’);
}

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

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

$result = $this-&amp;amp;amp;gt;Solr-&amp;amp;amp;gt;find(‘all’, $params);
$this-&amp;amp;amp;gt;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?