CakePHP
Using unBindModel() in CakePHP
In this article, we are going to discuss about How to use unBindModel() in CakePHP and the purpose of using unBindModel() in CakePHP. If you have a lot of associations in your model then it take a lot of time to return result. So to remove the unnecessary model in cakephp. we can use unBindModel(). By using unBindModel we can easily load a page more faster.
Sometimes you don't want all that information to be returned in a query which are associated in a model. The answer to this is to use the unBinModel() function. Using this you can unbind certain parts of your associations. The easiest way to demonstrate this is with an example.
If you have a user model with the following associations:
var $hasMany = array(
'Worksheet' => array('className' => 'Worksheet'
),
'Login' => array('className' => 'Login'
),
'Expense' => array('className' => 'Expense'
)
);
var $belongsTo = array(
'Level' =>
array('className' => 'Level'),
'County' =>
array('className' => 'County'),
'Province' =>
array('className' => 'Province')
);
That is potentially a lot of information with array of [Worksheet,Login,Expense,Level,Country,Province] each time you query the User.
So if we want to unbind Model (Login and Expense) we will write
$this->User->unBindModel(array(hasMany => array('Login', 'Expense')));
and we now call the findAll() function.
$this->User->findAll();
Now the result array will contain the of [User,Worksheet,Level,Country,Province] data.
we no longer return information from the Login and Expenses tables. This can be used for any of the associations and can cut down query times dramatically.
Sometimes you don't want all that information to be returned in a query which are associated in a model. The answer to this is to use the unBinModel() function. Using this you can unbind certain parts of your associations. The easiest way to demonstrate this is with an example.
If you have a user model with the following associations:
var $hasMany = array(
'Worksheet' => array('className' => 'Worksheet'
),
'Login' => array('className' => 'Login'
),
'Expense' => array('className' => 'Expense'
)
);
var $belongsTo = array(
'Level' =>
array('className' => 'Level'),
'County' =>
array('className' => 'County'),
'Province' =>
array('className' => 'Province')
);
That is potentially a lot of information with array of [Worksheet,Login,Expense,Level,Country,Province] each time you query the User.
So if we want to unbind Model (Login and Expense) we will write
$this->User->unBindModel(array(hasMany => array('Login', 'Expense')));
and we now call the findAll() function.
$this->User->findAll();
Now the result array will contain the of [User,Worksheet,Level,Country,Province] data.
we no longer return information from the Login and Expenses tables. This can be used for any of the associations and can cut down query times dramatically.
PHP CMS Frameworks
May 28, 2014
Read more →
Magento
Procedure to run Magento codes externally
In this article, we are going to discuss about how to run the Magento codes externally. If you're working with Magento often you'll find sometimes you need to use Magento functions and classes outside of the Magento platform. This can be easily achieved with the following lines of code.
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
// Now you can run ANY Magento code you want
// Change 12 to the ID of the product you want to load
$_product = Mage::getModel('catalog/product')->load(12);
echo $_product->getName();
This was only a quick post but hopefully it will be useful to someone.
Here's an example how to get the site navigation.
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
$_layout = Mage::getSingleton('core/layout');
$_block = $_layout->createBlock('catalog/navigation')->setTemplate('catalog/navigation/left.phtml');
echo $_block->toHtml();
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
// Now you can run ANY Magento code you want
// Change 12 to the ID of the product you want to load
$_product = Mage::getModel('catalog/product')->load(12);
echo $_product->getName();
This was only a quick post but hopefully it will be useful to someone.
Here's an example how to get the site navigation.
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
$_layout = Mage::getSingleton('core/layout');
$_block = $_layout->createBlock('catalog/navigation')->setTemplate('catalog/navigation/left.phtml');
echo $_block->toHtml();
PHP CMS Frameworks
May 25, 2014
Read more →
Zend
Extending ZfcUser module in Zend Framework 2
In this article, we are going to discuss about How to extend the ZfcUser module in Zend Framework 2. ZfcUser is a user registration and authentication module for Zend Framework 2. Out of the box, ZfcUser works with Zend\Db, however alternative storage adapter modules are available (see below). ZfcUser provides the foundations for adding user authentication and registration to your ZF2 site. It is designed to be very simple and easily to extend.
Creating Zend Framework 2 module
Zend Framework 2 uses a module system and we can organize our main application-specific code within each module.
The module system in ZF2 has been designed to be a generic and powerful foundation from which developers and other projects can build their own module or plugin systems.
The easiest way to create a new module is by using ZFTool. I think the easiest way to install it is to use a .phar file from that site and just pur it in your /vendor folder inside your project directory.
After you downloaded/installed ZFTool, run this in your console (I ran it inside vendor directory, if you are running from somewhere else, be sure to adjust the last parameter which is path to your project directory):
zftool.phar create module Blog ./
This will create a module called Blog with all the necessary folders and files needed for a module to function. It will also add your newly created module to modules array in your application.config.php file.
If you go to zf2blog.home/blog now, you will get an 404 error, which is fine as we don't have a controller and views for our module yet.
So, let's first adjust that, open /module/Blog/config/module.config.php and make it look like this:
return array(
'controllers' => array(
'invokables' => array(
'Blog\Controller\Blog' => 'Blog\Controller\BlogController'
),
),
'view_manager' => array(
'template_path_stack' => array(
'blog' => __DIR__ . '/../view',
),
),
);
Preparing Blog module
Let's prepare Blog module for further work. We will first add some routes to our module config file:
/module/Blog/config/module.config.php
...
// Routes
'router' => array(
'routes' => array(
'blog' => array(
'type' => 'segment',
'options' => array(
'route' => '/blog[/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Blog\Controller\Blog',
'action' => 'index',
),
),
),
),
),
...
Now, we need a Blog Controller and it's index Action and index view, so create
/module/Blog/src/Controller/BlogController.php
<?php
namespace Blog\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class BlogController extends AbstractActionController
{
/**
* (non-PHPdoc)
* @see \Zend\Mvc\Controller\AbstractActionController::indexAction()
*/
public function indexAction()
{
return new ViewModel();
}
}
and also create the view:
/module/Blog/view/blog/blog/index.phtml
<div class="page-header">
<h1><?php echo $this->translate('Blog'); ?></h1>
</div>
<div class="page-header">
<h1><?php echo $this->translate('Register'); ?></h1>
</div>
<?php
if (!$this->enableRegistration) {
print "Registration is disabled";
return;
}
$form = $this->registerForm;
$form->prepare();
$form->setAttribute('action', $this->url('zfcuser/register'));
$form->setAttribute('method', 'post');
echo $this->form()->openTag($form);
?>
<?php foreach ($form as $element) : ?>
<div style="width: 330px;" class="form-group <?php if ($this->formElementErrors($element)) echo "has-error" ?>">
<?php
if ('submit' != $element->getAttribute('type')) { ?>
<label class="control-label"><?php echo $element->getLabel() ?></label>
<?php
$element->setAttribute('class', 'form-control')
->setAttribute('placeholder', $element->getLabel());
} else {
$element->setAttribute('class', 'btn btn-success');
}
if ($element instanceof Zend\Form\Element\Captcha) {
echo $this->formCaptcha($element);
} else {
echo $this->formElement($element);
}
if ($this->formElementErrors($element)) : ?>
<?php
echo $this->formElementErrors()
->setMessageOpenFormat('<p class="help-block">')
->setMessageSeparatorString('</p><p class="help-block">')
->setMessageCloseString('</p>')
->render($element);
?>
<?php endif; ?>
</div>
<?php
endforeach;
if ($this->redirect): ?>
<input type="hidden" name="redirect" value="<?php echo $this->escapeHtml($this->redirect) ?>" />
<?php endif ?>
<?php echo $this->form()->closeTag() ?>
/module/Blog/view/zfc-user/user/login.phtml:
<div class="page-header">
<h1><?php echo $this->translate('Sign in'); ?></h1>
</div>
<?php
$form = $this->loginForm;
$form->prepare();
$form->setAttribute('action', $this->url('zfcuser/login'));
$form->setAttribute('method', 'post');
?>
<?php echo $this->form()->openTag($form) ?>
<?php foreach ($form as $element) : ?>
<div style="width: 330px;" class="form-group <?php if ($this->formElementErrors($element)) echo "has-error" ?>">
<?php
if ('submit' != $element->getAttribute('type')) { ?>
<label class="control-label"><?php echo $element->getLabel() ?></label>
<?php
$element->setAttribute('class', 'form-control')
->setAttribute('placeholder', $element->getLabel());
} else {
$element->setAttribute('class', 'btn btn-success');
}
echo $this->formElement($element);
if ($this->formElementErrors($element)) : ?>
<?php
echo $this->formElementErrors()
->setMessageOpenFormat('<p class="help-block">')
->setMessageSeparatorString('</p><p class="help-block">')
->setMessageCloseString('</p>')
->render($element);
?>
<?php endif; ?>
</div>
<?php
endforeach;
echo $this->form()->closeTag() ?>
<?php if ($this->enableRegistration) : ?>
<?php echo $this->translate('Not registered?'); ?> <a href="<?php echo $this->url('zfcuser/register') . ($this->redirect ? '?redirect='.$this->redirect : '') ?>"><?php echo $this->translate('Sign up!'); ?></a>
<?php endif; ?>
/module/Blog/view/zfc-user/user/index.phtml:
<div class="page-header">
<h1><?php echo $this->translate('User details'); ?></h1>
</div>
<div class="container">
<div class="row">
<div style="float:left; padding-right:16px;"><?php echo $this->gravatar($this->zfcUserIdentity()->getEmail()) ?></div>
<h3><?php echo $this->translate('Hello'); ?>, <?php echo $this->zfcUserDisplayName() ?>!</h3>
<a href="<?php echo $this->url('zfcuser/logout') ?>">[<?php echo $this->translate('Sign Out'); ?>]</a>
</div>
</div>
/module/Blog/view/zfc-user/user/changepassword.phtml:
<?php echo $this->form()->closeTag(); ?>
<div class="page-header">
<h1><?php echo sprintf($this->translate('Change Password for %s'), $this->zfcUserDisplayName()); ?></h1>
</div>
<?php if ($status === true) : ?>
<div class="alert alert-success"><?php echo $this->translate('Password changed successfully.');?></div>
<?php elseif ($status === false) : ?>
<div class="alert alert-danger"><?php echo $this->translate('Unable to update your password. Please try again.'); ?></div>
<?php endif; ?>
<?php
$form = $this->changePasswordForm;
$form->prepare();
$form->setAttribute('action', $this->url('zfcuser/changepassword'));
$form->setAttribute('method', 'post');
$emailElement = $form->get('identity');
$emailElement->setValue($this->zfcUserIdentity()->getEmail());
echo $this->form()->openTag($form);
?>
<?php foreach ($form as $element) : ?>
<div style="width: 330px;" class="form-group <?php if ($this->formElementErrors($element)) echo "has-error" ?>">
<?php
if ('submit' != $element->getAttribute('type')) { ?>
<label class="control-label"><?php echo $element->getLabel() ?></label>
<?php
$element->setAttribute('class', 'form-control')
->setAttribute('placeholder', $element->getLabel());
} else {
$element->setAttribute('class', 'btn btn-success');
}
if ($element instanceof Zend\Form\Element\Captcha) {
echo $this->formCaptcha($element);
} else {
echo $this->formElement($element);
}
if ($this->formElementErrors($element)) : ?>
<?php
echo $this->formElementErrors()
->setMessageOpenFormat('<p class="help-block">')
->setMessageSeparatorString('</p><p class="help-block">')
->setMessageCloseString('</p>')
->render($element);
?>
<?php endif; ?>
</div>
<?php
endforeach;?>
<?php if ($this->redirect): ?>
<input type="hidden" name="redirect" value="<?php echo $this->escapeHtml($this->redirect) ?>" />
<?php endif ?>
<?php echo $this->form()->closeTag() ?>
/module/Blog/view/zfc-user/user/changeemail.phtml:
<div class="page-header">
<h1><?php echo sprintf($this->translate('Change Email for %s'), $this->zfcUserDisplayName()); ?></h1>
</div>
<?php if ($status === true) : ?>
<div class="alert alert-success"><?php echo $this->translate('Email address changed successfully.'); ?></div>
<?php elseif ($status === false) : ?>
<div class="alert alert-danger"><?php echo $this->translate('Unable to update your email address. Please try again.'); ?></div>
<?php endif; ?>
<?php
$form = $this->changeEmailForm;
$form->prepare();
$form->setAttribute('action', $this->url('zfcuser/changeemail'));
$form->setAttribute('method', 'post');
echo $this->form()->openTag($form);
?>
<?php foreach ($form as $element) : ?>
<div style="width: 330px;" class="form-group <?php if ($this->formElementErrors($element)) echo "has-error" ?>">
<?php
if ('submit' != $element->getAttribute('type')) { ?>
<label class="control-label"><?php echo $element->getLabel() ?></label>
<?php
$element->setAttribute('class', 'form-control')
->setAttribute('placeholder', $element->getLabel());
} else {
$element->setAttribute('class', 'btn btn-success');
}
if ($element instanceof Zend\Form\Element\Captcha) {
echo $this->formCaptcha($element);
} else {
echo $this->formElement($element);
}
if ($this->formElementErrors($element)) : ?>
<?php
echo $this->formElementErrors()
->setMessageOpenFormat('<p class="help-block">')
->setMessageSeparatorString('</p><p class="help-block">')
->setMessageCloseString('</p>')
->render($element);
?>
<?php endif; ?>
</div>
<?php
endforeach;?>
<input class="btn btn-success" type="submit" value="Submit" />
<?php if ($this->redirect): ?>
<input type="hidden" name="redirect" value="<?php echo $this->escapeHtml($this->redirect) ?>" />
<?php endif ?>
<?php echo $this->form()->closeTag() ?>
This code is adjusting ZfcUser forms to Twitter Bootstrap markup. If you now go to zf2blog.home/user/register, you will see that the form looks awesome now. Even the validation messages looks better (try to submit the register form without entering the username).
Creating Zend Framework 2 module
Zend Framework 2 uses a module system and we can organize our main application-specific code within each module.
The module system in ZF2 has been designed to be a generic and powerful foundation from which developers and other projects can build their own module or plugin systems.
The easiest way to create a new module is by using ZFTool. I think the easiest way to install it is to use a .phar file from that site and just pur it in your /vendor folder inside your project directory.
After you downloaded/installed ZFTool, run this in your console (I ran it inside vendor directory, if you are running from somewhere else, be sure to adjust the last parameter which is path to your project directory):
zftool.phar create module Blog ./
This will create a module called Blog with all the necessary folders and files needed for a module to function. It will also add your newly created module to modules array in your application.config.php file.
If you go to zf2blog.home/blog now, you will get an 404 error, which is fine as we don't have a controller and views for our module yet.
So, let's first adjust that, open /module/Blog/config/module.config.php and make it look like this:
return array(
'controllers' => array(
'invokables' => array(
'Blog\Controller\Blog' => 'Blog\Controller\BlogController'
),
),
'view_manager' => array(
'template_path_stack' => array(
'blog' => __DIR__ . '/../view',
),
),
);
Preparing Blog module
Let's prepare Blog module for further work. We will first add some routes to our module config file:
/module/Blog/config/module.config.php
...
// Routes
'router' => array(
'routes' => array(
'blog' => array(
'type' => 'segment',
'options' => array(
'route' => '/blog[/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Blog\Controller\Blog',
'action' => 'index',
),
),
),
),
),
...
Now, we need a Blog Controller and it's index Action and index view, so create
/module/Blog/src/Controller/BlogController.php
<?php
namespace Blog\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class BlogController extends AbstractActionController
{
/**
* (non-PHPdoc)
* @see \Zend\Mvc\Controller\AbstractActionController::indexAction()
*/
public function indexAction()
{
return new ViewModel();
}
}
and also create the view:
/module/Blog/view/blog/blog/index.phtml
<div class="page-header">
<h1><?php echo $this->translate('Blog'); ?></h1>
</div>
That's it, if you point your browser to zf2blog.home/blog, you will see that it works.
Extending ZfcUser views
Let us now adjust ZfcUser views to Twitter Bootstrap 3 which is used in Zend Skeleton application we used. To override ZfcUser module's views, we just need to create a proper folders in our module's views folder and put the ZfcUser views we wish to override inside.
So create /module/Blog/view/zfc-user/user folder and add following files to it:
/module/Blog/view/zfc-user/user/register.phtml:
<div class="page-header">
<h1><?php echo $this->translate('Register'); ?></h1>
</div>
<?php
if (!$this->enableRegistration) {
print "Registration is disabled";
return;
}
$form = $this->registerForm;
$form->prepare();
$form->setAttribute('action', $this->url('zfcuser/register'));
$form->setAttribute('method', 'post');
echo $this->form()->openTag($form);
?>
<?php foreach ($form as $element) : ?>
<div style="width: 330px;" class="form-group <?php if ($this->formElementErrors($element)) echo "has-error" ?>">
<?php
if ('submit' != $element->getAttribute('type')) { ?>
<label class="control-label"><?php echo $element->getLabel() ?></label>
<?php
$element->setAttribute('class', 'form-control')
->setAttribute('placeholder', $element->getLabel());
} else {
$element->setAttribute('class', 'btn btn-success');
}
if ($element instanceof Zend\Form\Element\Captcha) {
echo $this->formCaptcha($element);
} else {
echo $this->formElement($element);
}
if ($this->formElementErrors($element)) : ?>
<?php
echo $this->formElementErrors()
->setMessageOpenFormat('<p class="help-block">')
->setMessageSeparatorString('</p><p class="help-block">')
->setMessageCloseString('</p>')
->render($element);
?>
<?php endif; ?>
</div>
<?php
endforeach;
if ($this->redirect): ?>
<input type="hidden" name="redirect" value="<?php echo $this->escapeHtml($this->redirect) ?>" />
<?php endif ?>
<?php echo $this->form()->closeTag() ?>
/module/Blog/view/zfc-user/user/login.phtml:
<div class="page-header">
<h1><?php echo $this->translate('Sign in'); ?></h1>
</div>
<?php
$form = $this->loginForm;
$form->prepare();
$form->setAttribute('action', $this->url('zfcuser/login'));
$form->setAttribute('method', 'post');
?>
<?php echo $this->form()->openTag($form) ?>
<?php foreach ($form as $element) : ?>
<div style="width: 330px;" class="form-group <?php if ($this->formElementErrors($element)) echo "has-error" ?>">
<?php
if ('submit' != $element->getAttribute('type')) { ?>
<label class="control-label"><?php echo $element->getLabel() ?></label>
<?php
$element->setAttribute('class', 'form-control')
->setAttribute('placeholder', $element->getLabel());
} else {
$element->setAttribute('class', 'btn btn-success');
}
echo $this->formElement($element);
if ($this->formElementErrors($element)) : ?>
<?php
echo $this->formElementErrors()
->setMessageOpenFormat('<p class="help-block">')
->setMessageSeparatorString('</p><p class="help-block">')
->setMessageCloseString('</p>')
->render($element);
?>
<?php endif; ?>
</div>
<?php
endforeach;
echo $this->form()->closeTag() ?>
<?php if ($this->enableRegistration) : ?>
<?php echo $this->translate('Not registered?'); ?> <a href="<?php echo $this->url('zfcuser/register') . ($this->redirect ? '?redirect='.$this->redirect : '') ?>"><?php echo $this->translate('Sign up!'); ?></a>
<?php endif; ?>
/module/Blog/view/zfc-user/user/index.phtml:
<div class="page-header">
<h1><?php echo $this->translate('User details'); ?></h1>
</div>
<div class="container">
<div class="row">
<div style="float:left; padding-right:16px;"><?php echo $this->gravatar($this->zfcUserIdentity()->getEmail()) ?></div>
<h3><?php echo $this->translate('Hello'); ?>, <?php echo $this->zfcUserDisplayName() ?>!</h3>
<a href="<?php echo $this->url('zfcuser/logout') ?>">[<?php echo $this->translate('Sign Out'); ?>]</a>
</div>
</div>
/module/Blog/view/zfc-user/user/changepassword.phtml:
<?php echo $this->form()->closeTag(); ?>
<div class="page-header">
<h1><?php echo sprintf($this->translate('Change Password for %s'), $this->zfcUserDisplayName()); ?></h1>
</div>
<?php if ($status === true) : ?>
<div class="alert alert-success"><?php echo $this->translate('Password changed successfully.');?></div>
<?php elseif ($status === false) : ?>
<div class="alert alert-danger"><?php echo $this->translate('Unable to update your password. Please try again.'); ?></div>
<?php endif; ?>
<?php
$form = $this->changePasswordForm;
$form->prepare();
$form->setAttribute('action', $this->url('zfcuser/changepassword'));
$form->setAttribute('method', 'post');
$emailElement = $form->get('identity');
$emailElement->setValue($this->zfcUserIdentity()->getEmail());
echo $this->form()->openTag($form);
?>
<?php foreach ($form as $element) : ?>
<div style="width: 330px;" class="form-group <?php if ($this->formElementErrors($element)) echo "has-error" ?>">
<?php
if ('submit' != $element->getAttribute('type')) { ?>
<label class="control-label"><?php echo $element->getLabel() ?></label>
<?php
$element->setAttribute('class', 'form-control')
->setAttribute('placeholder', $element->getLabel());
} else {
$element->setAttribute('class', 'btn btn-success');
}
if ($element instanceof Zend\Form\Element\Captcha) {
echo $this->formCaptcha($element);
} else {
echo $this->formElement($element);
}
if ($this->formElementErrors($element)) : ?>
<?php
echo $this->formElementErrors()
->setMessageOpenFormat('<p class="help-block">')
->setMessageSeparatorString('</p><p class="help-block">')
->setMessageCloseString('</p>')
->render($element);
?>
<?php endif; ?>
</div>
<?php
endforeach;?>
<?php if ($this->redirect): ?>
<input type="hidden" name="redirect" value="<?php echo $this->escapeHtml($this->redirect) ?>" />
<?php endif ?>
<?php echo $this->form()->closeTag() ?>
/module/Blog/view/zfc-user/user/changeemail.phtml:
<div class="page-header">
<h1><?php echo sprintf($this->translate('Change Email for %s'), $this->zfcUserDisplayName()); ?></h1>
</div>
<?php if ($status === true) : ?>
<div class="alert alert-success"><?php echo $this->translate('Email address changed successfully.'); ?></div>
<?php elseif ($status === false) : ?>
<div class="alert alert-danger"><?php echo $this->translate('Unable to update your email address. Please try again.'); ?></div>
<?php endif; ?>
<?php
$form = $this->changeEmailForm;
$form->prepare();
$form->setAttribute('action', $this->url('zfcuser/changeemail'));
$form->setAttribute('method', 'post');
echo $this->form()->openTag($form);
?>
<?php foreach ($form as $element) : ?>
<div style="width: 330px;" class="form-group <?php if ($this->formElementErrors($element)) echo "has-error" ?>">
<?php
if ('submit' != $element->getAttribute('type')) { ?>
<label class="control-label"><?php echo $element->getLabel() ?></label>
<?php
$element->setAttribute('class', 'form-control')
->setAttribute('placeholder', $element->getLabel());
} else {
$element->setAttribute('class', 'btn btn-success');
}
if ($element instanceof Zend\Form\Element\Captcha) {
echo $this->formCaptcha($element);
} else {
echo $this->formElement($element);
}
if ($this->formElementErrors($element)) : ?>
<?php
echo $this->formElementErrors()
->setMessageOpenFormat('<p class="help-block">')
->setMessageSeparatorString('</p><p class="help-block">')
->setMessageCloseString('</p>')
->render($element);
?>
<?php endif; ?>
</div>
<?php
endforeach;?>
<input class="btn btn-success" type="submit" value="Submit" />
<?php if ($this->redirect): ?>
<input type="hidden" name="redirect" value="<?php echo $this->escapeHtml($this->redirect) ?>" />
<?php endif ?>
<?php echo $this->form()->closeTag() ?>
This code is adjusting ZfcUser forms to Twitter Bootstrap markup. If you now go to zf2blog.home/user/register, you will see that the form looks awesome now. Even the validation messages looks better (try to submit the register form without entering the username).
PHP CMS Frameworks
May 21, 2014
Read more →
CakePHP
CakePHP - Loading Models Inside Other Models
In this article, we are going to discuss about How to load the models inside the another models. A model notifies its associated views and controllers when there has been a change in its state. This notification allows the views to produce updated output, and the controllers to change the available set of commands. In some cases an MVC implementation might instead be "passive," so that other components must poll the model for updates rather than being notified.
This is a really quick help that I'm always looking up is how to load CakePHP Models from within another Model, this is currently using version 2.x.
<?php
// the other model to load & use
App::uses('AnotherModel', 'Model');
class MyModel extends AppModel {
public $name = 'MyModel';
public function test() {
// load the Model
$anotherModel = new AnotherModel();
// use the Model
$anotherModel->save($data);
}
}
Instead of declaring uses at the top you can also import the Model class when you want to use it:
App::import('Model','AnotherModel');
$anotherModel = new AnotherModel();
$anotherModel->save($data);
This is a really quick help that I'm always looking up is how to load CakePHP Models from within another Model, this is currently using version 2.x.
<?php
// the other model to load & use
App::uses('AnotherModel', 'Model');
class MyModel extends AppModel {
public $name = 'MyModel';
public function test() {
// load the Model
$anotherModel = new AnotherModel();
// use the Model
$anotherModel->save($data);
}
}
Instead of declaring uses at the top you can also import the Model class when you want to use it:
App::import('Model','AnotherModel');
$anotherModel = new AnotherModel();
$anotherModel->save($data);
PHP CMS Frameworks
May 14, 2014
Read more →
CakePHP
Create custom Route classes and Pagination in CakePHP
In this article, we are going to discuss about How to create a custom Route classes and pagination in CakePHP. Recently I have faces some issues with the buit-in Paginator Helper when combined with custom routes. I have the site setup so that admins can create Category pages with unique URL slugs so that they can edit pages and also get nice URLs like so:
http://local.example.co.uk/category
http://local.example.co.uk/category/sub-category
I've set this up in CakePHP using a custom Route class as per the docs and this works great. Below I've got the routes.php code to check for a Category slug and use the view action of the ProductCategories Controller.
// app\Config\routes.php file
Router::connect('/:slug/*', array('controller' => 'product_categories', 'action' => 'view'), array('routeClass' => 'CategorySlugRoute'));
This is the Route class code, which is pretty straight forward just in case you need to do anything similar. I've added caching to speed things up and the only caveat are the sub-categories; as these are separated with a forward slash we have to rebuild them to ensure we're checking the slugs for sub categories as well as top level categories.
<?php
/**
* Deal with Category Slugs
*/
App::uses('ProductCategory', 'Model');
class CategorySlugRoute extends CakeRoute {
/**
* Parse the URL
* @param string $url
* @return boolean
*/
function parse($url) {
$params = parent::parse($url);
if (empty($params)) {
return false;
}
// See if slugs are cached
$slugs = Cache::read('slugs_categories');
if (!$slugs) {
// Get all slugs
$ProductCategory = new ProductCategory();
$slugs = $ProductCategory->find('list', array(
'fields' => array('ProductCategory.slug'),
'recursive' => -1
));
Cache::write('slugs_categories', $slugs);
}
// Reverse slugs for easy comparison
$slugs = array_flip($slugs);
// See if sub categories have been passed
if (!empty($params['pass'])) {
$params['slug'] .= '/' . implode('/', $params['pass']);
}
// Match passed slug with Category slugs
if (isset($slugs[$params['slug']])) {
return $params;
}
return FALSE;
}
}
When it came to paginating those result it wasn't clear how to take advantage of the custom slug I was using. I tried a few different solutions however all the generated pagination links all included the /product_categories/view in the URL which is incorrect.
To fix the links I had to pass in the slug as a url Paginator option before the calls to generate the links. After this CakePHP knew what was going on and correctly built the correct URL.
<?php
// app\View\ProductCategories\index.ctp
$this->Paginator->options(array('url' => array('slug' => $category['ProductCategory']['slug'])));
echo $this->Paginator->prev('Prev');
echo $this->Paginator->numbers();
echo $this->Paginator->next('Next');
?>
http://local.example.co.uk/category
http://local.example.co.uk/category/sub-category
I've set this up in CakePHP using a custom Route class as per the docs and this works great. Below I've got the routes.php code to check for a Category slug and use the view action of the ProductCategories Controller.
// app\Config\routes.php file
Router::connect('/:slug/*', array('controller' => 'product_categories', 'action' => 'view'), array('routeClass' => 'CategorySlugRoute'));
This is the Route class code, which is pretty straight forward just in case you need to do anything similar. I've added caching to speed things up and the only caveat are the sub-categories; as these are separated with a forward slash we have to rebuild them to ensure we're checking the slugs for sub categories as well as top level categories.
<?php
/**
* Deal with Category Slugs
*/
App::uses('ProductCategory', 'Model');
class CategorySlugRoute extends CakeRoute {
/**
* Parse the URL
* @param string $url
* @return boolean
*/
function parse($url) {
$params = parent::parse($url);
if (empty($params)) {
return false;
}
// See if slugs are cached
$slugs = Cache::read('slugs_categories');
if (!$slugs) {
// Get all slugs
$ProductCategory = new ProductCategory();
$slugs = $ProductCategory->find('list', array(
'fields' => array('ProductCategory.slug'),
'recursive' => -1
));
Cache::write('slugs_categories', $slugs);
}
// Reverse slugs for easy comparison
$slugs = array_flip($slugs);
// See if sub categories have been passed
if (!empty($params['pass'])) {
$params['slug'] .= '/' . implode('/', $params['pass']);
}
// Match passed slug with Category slugs
if (isset($slugs[$params['slug']])) {
return $params;
}
return FALSE;
}
}
When it came to paginating those result it wasn't clear how to take advantage of the custom slug I was using. I tried a few different solutions however all the generated pagination links all included the /product_categories/view in the URL which is incorrect.
To fix the links I had to pass in the slug as a url Paginator option before the calls to generate the links. After this CakePHP knew what was going on and correctly built the correct URL.
<?php
// app\View\ProductCategories\index.ctp
$this->Paginator->options(array('url' => array('slug' => $category['ProductCategory']['slug'])));
echo $this->Paginator->prev('Prev');
echo $this->Paginator->numbers();
echo $this->Paginator->next('Next');
?>
PHP CMS Frameworks
May 11, 2014
Read more →
CodeIgniter
CIBB - Basic Forum With Codeigniter and Twitter Bootstrap
In this article, we are going to discuss about How to create basic forum CIBB (CodeIgniter Bulletin Board) with CodeIgniter and Twitter Bootstrap.
For learning more about using twitter bootstrap I made this and completely using a basic bootstrap style, I have created only a very basic forum software. So do not expect to much features from it, but you can download and use it for any kind of purpose.
Features
Installation
I have not created the web installer yet. So you have to manually export the sql file (cibb.sql) to your mysql administrator, and on the web change the $config['base_url'] in config.php and change databse value in database.php, like in official codeigniter user guide.
Sample Screen
thread index
thread talk
list of roles
To download the source files Click Here
For learning more about using twitter bootstrap I made this and completely using a basic bootstrap style, I have created only a very basic forum software. So do not expect to much features from it, but you can download and use it for any kind of purpose.
Features
- User roles management
- Rich text editor using jWysiwyg
- Threaded category
- Basic forum (create thread, post reply)
Installation
I have not created the web installer yet. So you have to manually export the sql file (cibb.sql) to your mysql administrator, and on the web change the $config['base_url'] in config.php and change databse value in database.php, like in official codeigniter user guide.
Sample Screen
thread index

thread talk


To download the source files Click Here
PHP CMS Frameworks
May 07, 2014
Read more →
CakePHP
Step to use media view in cakephp controller
In this article, we are going to discuss about How to use the Media view in the cakephp controller. In cakephp Media views allow you to send binary files to the user. For example, you may wish to have a directory of files outside of the webroot to prevent users from direct linking them.
You can use the Media view to pull the file from a special folder within /app/, allowing you to perform authentication before delivering the file to the user.
To use the Media view, you need to tell your controller to use the MediaView class instead of the default View class. After that, just pass in additional parameters to specify where your file is located.
class ExampleController extends AppController {
function download () {
$this->view = 'Media';
$params = array(
'id' => 'example.zip',
'name' => 'example',
'download' => true,
'extension' => 'zip', // must be lower case
'path' => APP . 'files' . DS // don't forget terminal 'DS'
);
$this->set($params);
}
}
You can use the Media view to pull the file from a special folder within /app/, allowing you to perform authentication before delivering the file to the user.
To use the Media view, you need to tell your controller to use the MediaView class instead of the default View class. After that, just pass in additional parameters to specify where your file is located.
class ExampleController extends AppController {
function download () {
$this->view = 'Media';
$params = array(
'id' => 'example.zip',
'name' => 'example',
'download' => true,
'extension' => 'zip', // must be lower case
'path' => APP . 'files' . DS // don't forget terminal 'DS'
);
$this->set($params);
}
}
PHP CMS Frameworks
May 04, 2014
Read more →
No more posts to load.
About this blog
PHPCMSFramework.com
Tutorials for WordPress, Laravel, Drupal, Joomla, Symfony & more — including AI-powered PHP guides. Publishing since 2012.
Trending posts
- Building a RAG System in Laravel from Scratch
- Steps to create a Contact Form in Symfony With SwiftMailer
- Build an AI Code Review Bot with Laravel — Real-World Use Case
- Build a WhatsApp AI Assistant Using Laravel, Twilio and OpenAI
- CIBB - Basic Forum With Codeigniter and Twitter Bootstrap
- Drupal 7 - Create your custom Hello World module
- Laravel and Prism PHP: The Modern Way to Work with AI Models
- Create Front End Component in Joomla - Step by step procedure
- A step by step procedure to develop wordpress plugin
- Symfony Framework - Introduction
Blog Archive
-
▼
2014
(86)
-
▼
May
(7)
- Using unBindModel() in CakePHP
- Procedure to run Magento codes externally
- Extending ZfcUser module in Zend Framework 2
- CakePHP - Loading Models Inside Other Models
- Create custom Route classes and Pagination in CakePHP
- CIBB - Basic Forum With Codeigniter and Twitter Bo...
- Step to use media view in cakephp controller
-
▼
May
(7)