We build custom web applications
to grow your business.

CakePHP tips and tricks

// CREATE SLUG
Inflector::pluralize($singular)
other purposes: camelize, underscore, humanize, tablesize, classify, variable, slug

// HTTP REQUEST
App::uses('HttpSocket', 'Network/Http');
$HttpSocket = new HttpSocket();

// STRING QUERY GET
$results = $HttpSocket->get('http://www.google.com/search', 'q=cakephp');

// ARRAY QUERY GET
$results = $HttpSocket->get('http://www.google.com/search', array('q' => 'cakephp'));

// In HTACCESS route url to WWW
RewriteCond "%{HTTP_HOST}" "!^www\."                    [NC]
RewriteCond "%{HTTP_HOST}" "!^$"
RewriteRule "^/?(.*)"      "http://www.%{HTTP_HOST}/$1" [L,R,NE]

// CREATE MYSQL TABLE IN CONTROLLER
App::import('Model', 'ConnectionManager');
        $con = new ConnectionManager;
        $cn = $con->getDataSource('default');
        $cn->query("CREATE table relatedproducts (
            id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            product_id int(11),
            imageOne int(11),
            imageTwo int(11),
            imageThree int(11),
            imageFour int(11)
            )");

// ORDER BY QUERY IN MODEL
public function beforeFind($queryData) {
        //parent::beforeFind();
        $queryData['order'] = array('id DESC');
        return $queryData;      
    }

// ACCESSING APPCONTROLLER FUNCTION IN CONTROLLER
function beforeFilter()
  {
  $this->set('settings', $settings);
  }

$this->viewVars['settings']['emails'] // in the controller

// SET TIME ZONE IN BOOTSTRAP.PHP
date_default_timezone_set("America/Chicago");

// CAKEPHP SELECT WITH IF STATEMENT
$query = sprintf("SELECT * FROM table ". $var != 0 ? "WHERE var = '%s'" : "");

// PRINTING USER INFORMATION AFTER LOGIN
<?php print $this->Session->read('Auth.User.username'); ?>

// CHECK IF USER IS LOGIN
<?php if(AuthComponent::user('id')) { ?>

// GET USER INFORMATION FROM THE APPCONTROLLER
Configure::write('User', $this->Auth->user());

// GET USER INFORMATION ANYWHERE
Configure::read('User.id');

// GET THE MODEL OBJECT(schema and associations)
$modelClass = $this->modelClass;
$Model = ClassRegistry::init($modelClass);

// GET THE TYPE OF EACH MYSQL FIELD
$modelKey = $this->model();
$fieldKey = $this->field();
$type = $this->_introspectModel($modelKey, 'fields', $fieldKey);

result return should be like this

Array
(
    [type] => decimal
    [null] => 1
    [default] => 
    [length] => 16,2
    [unsigned] => 
    [comment] => Minimum amount you can bid above current high bid.
)

// SHOW ALL FIELDS IN THE TABLE
pr($Model->schema());

// SEE WHICH USER CREATED EACH POST
function index() {
$this->paginate = array('contain' => 'User');
$this->set('posts', $this->paginate());
}

// FINDING TAGS
$Post->find('latest')
or $Post->find('tag', array('php', 'beer', 'nsfw')).

// THREE WAYS TO GET MODEL DATA
(1) var $name = 'Posts';
var $uses = array('Post', 'Comment');
$comments = $this->Post->Comment->findAllByPostId($id);

2. the loadModel way
$this->loadModel('Comment');
$comments = $this->Comment->findAllByPostId($id);

3. the ClassRegistry way
$Comment = ClassRegistry::init('Comment');
$comments = $Comment->findAllByPostId($id);

// SENDING TEXT MESSAGES
$ms = wordwrap('this is a text my friend',65);
mail('2564298145@vtext.com', '', $ms );    

// BAKING ADMIN

1. first bake all models
Console/cake bake model all

2. Then bake controller and view
Console/cake bake controller all --admin
// specific controller
Console/cake bake controller <controller> --admin

3. in cakePHP3.0
cake bake controller users --prefix admin

CREATE CUSTOM PAGINATION
Please remove pagination component for this to work

public $paginate = [
        'limit' => 10,
        'conditions' => [
            'is_expired' => false,
            'is_sold' => false,
            'is_public' => true
        ],
        'order' => [
            'Auction.id' => 'DESC'
        ]
    ];   

2. Paginate in another method of the same controller
public function admin_index() {
        $this->Auction->recursive = 0;
        $this->paginate = [
            'limit' => 20,        
            'order' => [
                'Auction.id' => 'DESC'
            ]
        ];        
        $this->set('auctions', $this->paginate());
    }

3. Paginate with JOINS
$this->paginate['joins'] = array( array(
                    'table' => 'categorized',
                    'alias' => 'Categorized',
                    'type' => 'INNER',
                    'conditions' => array(
                        "Categorized.foreign_key = Auction.id",
                        "Categorized.model = 'Auction'",
                        "Categorized.category_id = '{$categoryId}'",
                    ),
                ));

GET REQUEST PARAMS VARIABLES
1. controller
<?=$this->params['controller']?>

2. action
<?=$this->params['action']?>

3. pass (parameter)
<?=$this->params['pass'][0]?>

MERGE ADD AND EDIT ACTION
function edit($id = null) {    
if (!empty($this->data)) {        
if ($this->Post->save($this->data)) {            
$this->flash(__('The Post has been saved.', true),                          array('action'=>'index'));        

} else {        
}   
}    
if ($id && empty($this->data)) {        
$this->data = $this->Post->read(null, $id);    
}
}
// add the following to router
Router::connect('/:controller/add', array('action' => 'edit', 'origAction' => 'add'));
// add this to the edit view and delete the add veiw
$action = !empty($this->params['origAction']) ? $this>params['origAction'] : $this->action;

USING THE OPTION PARAMENT FOR MULTIPLE PARAMETERS
// turn this
public function product($product_id=null, $user_id=null, $start_date=null)
// into this
public function product($options = array()) {   
    $options = array_merge(array(
        'product_id' => $this->id,
                'user_id' => User::get('id'),
         start_date' => strtotime('-2 month'),                                            
         $options));
}
 

CREATING BEAUTIFUL URLS FOR YOUR VIEW
your view is like
public function view($id=null) {}
your url will be like this www.yourwebsite.com/post/view/7
Now, to get all your link url to be like this www.yourwebsite.com/post/view/7/i-love-cakephp add the Slug Inflector to the title
$html->link($post['Post']['title'], array(
controller' => 'Post', 'action' => 'view',$post['Post']['id'],  Inflector::slug($post['Post']['title'], '-') )
);

// add this to the view action to prevent malicous links
If(Inflector::slug($post['Post']['title']) != $this->params['pass'][1]   || count($this->params['pass']) != 2) {  
    $post = $this->Post->read(null, $id);  
    $this->redirect(array($id,Inflector::slug($post['Post']['title']), 301));
}

// ADDING UNIQUE DATA TO DATABASE

if ($this->Demo->isUnique(array(
					'User.first_name'=>$this->request->data['User']['first_name'], 
					'User.last_name'=>$this->request->data['User']['last_name']					
					), false
					)) {
					$this->User->Save($this->request->data['User']);
					unset($this->request->data['User']);
				}