CodeIgniter
Steps to implement Memcache in Codeigniter
In this article, we are going to discuss about How to implement memcache in CodeIgniter (CI). Memcache is used to increase the performance of the websute (ie, speed-up the website) by using the memory space of our used domains and store the database query results in that cache and minimise the application-database interaction.
Step 1:
Before we implement Memcache in CodeIgniter (CI), we need to check whether the memcache is enabled in our web server or not. If it is not enabled, then enable it by uncomment the 'extension=php_memcache.dll' in php.ini file in the server. (Just remove the ";" symbol infront of the line).
Step 2:
Download the Memcache executable file to install the Memcache in the webserver. To download the Memacache executable file, Click on the below link
Download link - http://code.jellycan.com/files/memcached-1.2.6-win32-bin.zip
Step 3:
Once downloaed, Unzip the downloaded file, you will get a memcached executable file. Store that in a web server to install.
Step 4:
Then open the command prompt and run this command
c:/xampp/htdocs/memcached.exe -d install
then run the below command
'c:/xampp/htdocs/memcached.exe -d start'
Step 5:
Download the cache driver from the below URL
http://d45jz936mo8n8.cloudfront.net/wp-content/uploads/2010/01/Cache.php_1.zip
Once downloaded, Unzip and place the cache.php in system/libraries/cache folder.
Step 6:
Create an empty folder named "cache" on the location system folder.
Step 7:
Load the Cache driver in controller CodeIgniter (CI) application
$this->load->driver('cache');
Add the following lines of code where needed to cache the query result.
$cache = $this->cache->get('cache_data');
if($cache)
{
$data = $this->cache->get('cache_data');
}
else
{
$data = $this->sample_model->get_data();
$this->cache->save('cache_data', $data, NULL, 3600);
}
While accessing the webpage, it will execute query on the database for the first time, then the result will be stored in cache upto the refreshing time given in the save() function above.
So until the time exceeds, whenever the user refreshes the page, the application will not interact with the database. instead it will retrieve from cache and display.
This caching is applicable only for the select queries and the static updates.
Step 1:
Before we implement Memcache in CodeIgniter (CI), we need to check whether the memcache is enabled in our web server or not. If it is not enabled, then enable it by uncomment the 'extension=php_memcache.dll' in php.ini file in the server. (Just remove the ";" symbol infront of the line).
Step 2:
Download the Memcache executable file to install the Memcache in the webserver. To download the Memacache executable file, Click on the below link
Download link - http://code.jellycan.com/files/memcached-1.2.6-win32-bin.zip
Step 3:
Once downloaed, Unzip the downloaded file, you will get a memcached executable file. Store that in a web server to install.
Step 4:
Then open the command prompt and run this command
c:/xampp/htdocs/memcached.exe -d install
then run the below command
'c:/xampp/htdocs/memcached.exe -d start'
Step 5:
Download the cache driver from the below URL
http://d45jz936mo8n8.cloudfront.net/wp-content/uploads/2010/01/Cache.php_1.zip
Once downloaded, Unzip and place the cache.php in system/libraries/cache folder.
Step 6:
Create an empty folder named "cache" on the location system folder.
Step 7:
Load the Cache driver in controller CodeIgniter (CI) application
$this->load->driver('cache');
Add the following lines of code where needed to cache the query result.
$cache = $this->cache->get('cache_data');
if($cache)
{
$data = $this->cache->get('cache_data');
}
else
{
$data = $this->sample_model->get_data();
$this->cache->save('cache_data', $data, NULL, 3600);
}
While accessing the webpage, it will execute query on the database for the first time, then the result will be stored in cache upto the refreshing time given in the save() function above.
So until the time exceeds, whenever the user refreshes the page, the application will not interact with the database. instead it will retrieve from cache and display.
This caching is applicable only for the select queries and the static updates.
PHP CMS Frameworks
November 27, 2013
Read more →
CodeIgniter
Execute Cron Job in CodeIgniter using PHP Curl
In this article we are going to discuss about, How to execute Cron Job in CodeIgniter (CI) using PHP. Codeigniter (CI) runs based on the front controller pattern where all the requests are routed using the index.php file. So we need to go through the routing procedures to execute any code on CodeIgniter (CI) application. Basically if we need to run cron job, we need to create the code files and placed it in the server and call the files in the cron job using path to files.
But in CodeIgniter (CI) applications, it is not much easy to call the cron job files and use CodeIgniter models inside this scripts. You need to load all the required models and files manually. We cannot achieve this using normal php script calling procedure.
Curl:
PHP Curl extension is used to transfer data from server to another server using various methods. In this example we need to execute a remote url using normal http method in curl.
Steps to install Curl in Windows:
You have to allow the curl extension by removing ';' in the php.ini file and restart apache server.
Steps to install Curl in Fedora:
Type the following command in the terminal using the super user.
yum install php-curl
Steps to install Curl in Ubuntu:
Type the following command in the terminal using the super user.
apt-get install php-curl
Setting the Cronjob using Curl
You can set up the cronjob to call the CodeIgniter (CI) url using the following line of code.
/usr/bin/curl http://www.example.com/controller/cron_function
Open the crontab using the terminal and enter the above line of code and restart the cron. Use the path to the curl file according to your installed location. Call the cron function of your site remotely using http.
But in CodeIgniter (CI) applications, it is not much easy to call the cron job files and use CodeIgniter models inside this scripts. You need to load all the required models and files manually. We cannot achieve this using normal php script calling procedure.
Curl:
PHP Curl extension is used to transfer data from server to another server using various methods. In this example we need to execute a remote url using normal http method in curl.
Steps to install Curl in Windows:
You have to allow the curl extension by removing ';' in the php.ini file and restart apache server.
Steps to install Curl in Fedora:
Type the following command in the terminal using the super user.
yum install php-curl
Steps to install Curl in Ubuntu:
Type the following command in the terminal using the super user.
apt-get install php-curl
Setting the Cronjob using Curl
You can set up the cronjob to call the CodeIgniter (CI) url using the following line of code.
/usr/bin/curl http://www.example.com/controller/cron_function
Open the crontab using the terminal and enter the above line of code and restart the cron. Use the path to the curl file according to your installed location. Call the cron function of your site remotely using http.
PHP CMS Frameworks
November 24, 2013
Read more →
Magento
Magento - Create an external Database Connection
Normally we are all experienced with connecting the database with Magento. But in this article, we are going to discuss about How to create an external database connection in Magento. Hopefully, by presenting this code here, I can save you from the pain I endured :)
Creating a database Connection
To create a new connection, create a custom module and add the following codes to your config.xml. The code below is needed to get the external database connection working.
<?xml version="1.0"?>
<config>
<modules>
<PHPCmsframework_Externaldb>
<version>0.1.0</version>
</PHPCmsframework_Externaldb>
</modules>
<global>
<resources>
<externaldb_write>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_write>
<externaldb_read>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_read>
<externaldb_setup>
<connection>
<use>core_setup</use>
</connection>
</externaldb_setup>
<externaldb_database>
<connection>
<host><![CDATA[localhost]]></host>
<username><![CDATA[db_username]]></username>
<password><![CDATA[db_password]]></password>
<dbname><![CDATA[db_name]]></dbname>
<model>mysql4</model>
<type>pdo_mysql</type>
<active>1</active>
</connection>
</externaldb_database>
</resources>
</global>
</config>
Clear the cache after creating your new module and from now on, each time you load Magento, a second database connection will be created.
Accessing an external Database
When I initially checked out how to create an external database connection, I was using Zend_Db to retrieve all of my information. You can use the following to test your database connection is working:
<?php
$resource = Mage::getSingleton('core/resource');
$conn = $resource->getConnection('externaldb_read');
$results = $conn->query('SELECT * FROM tblName');
print_r($results);
The above code is working fine, however kind of takes the point away from having this connection available in Magento.
Accessing an External Database Using Models
Using models to access the database keeps our code style uniform throughout Magento. Also, it means we can integrate any other CMS or database driven application without learning it's coding practices. To achieve this, simply add models to your custom module like you would for any other module.
I will attempt to demonstrate how to set up the models and config.xml files now.
Creating The Model Class Files
Create the following files:
code/local/PHPCmsframework/Externaldb/Model/Book.php
<?php
class PHPCmsframework_Externaldb_Model_Book extends Mage_Core_Model_Abstract
{
public function _construct()
{
$this->_init('externaldb/book');
}
}
code/local/PHPCmsframework/Externaldb/Model/Mysql4/Book.php
<?php
class PHPCmsframework_Externaldb_Model_Mysql4_Book extends Mage_Core_Model_Mysql4_Abstract
{
public function _construct()
{
$this->_init('externaldb/book', 'book_id'); // book_id refers to the primary key of the book table
}
}
code/local/PHPCmsframework/Externaldb/Model/Mysql4/Book/Collection.php
<?php
class PHPCmsframework_Externaldb_Model_Mysql4_Book_Collection extends Mage_Core_Model_Mysq4_Collection_Abstract
{
public function _construct()
{
$this->_init('externaldb/book');
}
}
That's the minimum needed for your models to be able to access an external database!
Adding the Models to The Config
To inform Magento about our models, we need to register them in config.xml. Below is an updated version of config.xml with the models for Book registered.
<?xml version="1.0"?>
<config>
<modules>
<PHPCmsframework_Externaldb>
<version>0.1.0</version>
</PHPCmsframework_Externaldb>
</modules>
<global>
<models>
<externaldb>
<class>PHPCmsframework_Externaldb_Model</class>
<resourceModel>externaldb_mysql4</resourceModel>
</externaldb>
<externaldb_mysql4>
<class>PHPCmsframework_Externaldb_Model_Mysql4</class>
<entities>
<book>
<table>library_book</table>
</book>
</entities>
</externaldb_mysql4>
</models>
<resources>
<externaldb_write>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_write>
<externaldb_read>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_read>
<externaldb_setup>
<connection>
<use>core_setup</use>
</connection>
</externaldb_setup>
<externaldb_database>
<connection>
<host><![CDATA[localhost]]></host>
<username><![CDATA[db_username]]></username>
<password><![CDATA[db_password]]></password>
<dbname><![CDATA[db_name]]></dbname>
<model>mysql4</model>
<type>pdo_mysql</type>
<active>1</active>
</connection>
</externaldb_database>
</resources>
</global>
</config>
That's it, the models should now be registered in Magento!
Testing The Models
Testing them is easy enough, just treat them like normal Magento models.
<?php
// Load the book with a primary key value of 4
$_book = Mage::getModel('externaldb/book')->load(4);
// This would print out the value in the field isbn in the external database
echo $_book->getIsbn();
//You can even update records!
$_book->setName('1984');
$_book->setAuthor('George Orwell');
try {
$_book->save();
} catch (Exception $e) {
exit($e->getMessage());
}
This is one of my favaourite article. So I probably haven't written this up as well as I could have, however, I think that using a second database in Magento can be extremely useful.
Creating a database Connection
To create a new connection, create a custom module and add the following codes to your config.xml. The code below is needed to get the external database connection working.
<?xml version="1.0"?>
<config>
<modules>
<PHPCmsframework_Externaldb>
<version>0.1.0</version>
</PHPCmsframework_Externaldb>
</modules>
<global>
<resources>
<externaldb_write>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_write>
<externaldb_read>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_read>
<externaldb_setup>
<connection>
<use>core_setup</use>
</connection>
</externaldb_setup>
<externaldb_database>
<connection>
<host><![CDATA[localhost]]></host>
<username><![CDATA[db_username]]></username>
<password><![CDATA[db_password]]></password>
<dbname><![CDATA[db_name]]></dbname>
<model>mysql4</model>
<type>pdo_mysql</type>
<active>1</active>
</connection>
</externaldb_database>
</resources>
</global>
</config>
Clear the cache after creating your new module and from now on, each time you load Magento, a second database connection will be created.
Accessing an external Database
When I initially checked out how to create an external database connection, I was using Zend_Db to retrieve all of my information. You can use the following to test your database connection is working:
<?php
$resource = Mage::getSingleton('core/resource');
$conn = $resource->getConnection('externaldb_read');
$results = $conn->query('SELECT * FROM tblName');
print_r($results);
The above code is working fine, however kind of takes the point away from having this connection available in Magento.
Accessing an External Database Using Models
Using models to access the database keeps our code style uniform throughout Magento. Also, it means we can integrate any other CMS or database driven application without learning it's coding practices. To achieve this, simply add models to your custom module like you would for any other module.
I will attempt to demonstrate how to set up the models and config.xml files now.
Creating The Model Class Files
Create the following files:
code/local/PHPCmsframework/Externaldb/Model/Book.php
<?php
class PHPCmsframework_Externaldb_Model_Book extends Mage_Core_Model_Abstract
{
public function _construct()
{
$this->_init('externaldb/book');
}
}
code/local/PHPCmsframework/Externaldb/Model/Mysql4/Book.php
<?php
class PHPCmsframework_Externaldb_Model_Mysql4_Book extends Mage_Core_Model_Mysql4_Abstract
{
public function _construct()
{
$this->_init('externaldb/book', 'book_id'); // book_id refers to the primary key of the book table
}
}
code/local/PHPCmsframework/Externaldb/Model/Mysql4/Book/Collection.php
<?php
class PHPCmsframework_Externaldb_Model_Mysql4_Book_Collection extends Mage_Core_Model_Mysq4_Collection_Abstract
{
public function _construct()
{
$this->_init('externaldb/book');
}
}
That's the minimum needed for your models to be able to access an external database!
Adding the Models to The Config
To inform Magento about our models, we need to register them in config.xml. Below is an updated version of config.xml with the models for Book registered.
<?xml version="1.0"?>
<config>
<modules>
<PHPCmsframework_Externaldb>
<version>0.1.0</version>
</PHPCmsframework_Externaldb>
</modules>
<global>
<models>
<externaldb>
<class>PHPCmsframework_Externaldb_Model</class>
<resourceModel>externaldb_mysql4</resourceModel>
</externaldb>
<externaldb_mysql4>
<class>PHPCmsframework_Externaldb_Model_Mysql4</class>
<entities>
<book>
<table>library_book</table>
</book>
</entities>
</externaldb_mysql4>
</models>
<resources>
<externaldb_write>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_write>
<externaldb_read>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_read>
<externaldb_setup>
<connection>
<use>core_setup</use>
</connection>
</externaldb_setup>
<externaldb_database>
<connection>
<host><![CDATA[localhost]]></host>
<username><![CDATA[db_username]]></username>
<password><![CDATA[db_password]]></password>
<dbname><![CDATA[db_name]]></dbname>
<model>mysql4</model>
<type>pdo_mysql</type>
<active>1</active>
</connection>
</externaldb_database>
</resources>
</global>
</config>
That's it, the models should now be registered in Magento!
Testing The Models
Testing them is easy enough, just treat them like normal Magento models.
<?php
// Load the book with a primary key value of 4
$_book = Mage::getModel('externaldb/book')->load(4);
// This would print out the value in the field isbn in the external database
echo $_book->getIsbn();
//You can even update records!
$_book->setName('1984');
$_book->setAuthor('George Orwell');
try {
$_book->save();
} catch (Exception $e) {
exit($e->getMessage());
}
This is one of my favaourite article. So I probably haven't written this up as well as I could have, however, I think that using a second database in Magento can be extremely useful.
PHP CMS Frameworks
November 20, 2013
Read more →
Magento
Magento - Load a Category OR Product by an attribute
In this article, we are going to discuss about How to load a categort or a product by an attribute. Most of the developers are often searching for how to load a product by a particular attribute. This article is quite easy to achieve this in Magento and can be done using Magento collections.
Load a Product By SKU
In magento, we have lot of pre defined product attributes. SKU is a static attribute. This means that instead of being stored in one of the products EAV tables, it is stored in the main product entity table (catalog_product_entity). This makes loading a product based on it's SKU much easier and efficient.
<?php
$sku = 'my-product-sku';
$product = Mage::getModel('catalog/product')->load($sku, 'sku');
if ($product->getId()) {
echo $product->getName();
}
else {
echo 'Product not found with SKU of ' . $sku;
}
The above code is used to makes the use of load method, which is available for all EAV entities in Magento. By default this method takes two parameters:
Load a Product By SKU
In magento, we have lot of pre defined product attributes. SKU is a static attribute. This means that instead of being stored in one of the products EAV tables, it is stored in the main product entity table (catalog_product_entity). This makes loading a product based on it's SKU much easier and efficient.
<?php
$sku = 'my-product-sku';
$product = Mage::getModel('catalog/product')->load($sku, 'sku');
if ($product->getId()) {
echo $product->getName();
}
else {
echo 'Product not found with SKU of ' . $sku;
}
The above code is used to makes the use of load method, which is available for all EAV entities in Magento. By default this method takes two parameters:
- A value that is used to match the product and the field that the values is checked against.
- If the second parameter is empty, Magento will use the primary key, which is usually the model ID. By passing a static attribute (SKU is the only useful static attribute for this context), it is possible to load a product model on a different value.
Load a product by an Attribute
The most of product attributes that you work with in Magento will not be static attributes and their values will be separated across several different tables. oading a product by a value that's stored like this is less efficient as several Magento tables will need to be joined to locate the product you are looking for. This doesn't mean that you shouldn't do it, it's just always good to be aware of such performance factors.
<?php
// Instantiate a product collection object
$products = Mage::getResourceModel('catalog/product_collection');
// Select which fields to load into the product
// * will load all fields but it is possible to pass an array of
// select fields to load
$products->addAttributeToSelect('*');
// Ensure the product is visible
$products->addAttributeToFilter('visibility', array('neq' => 1));
// Ensure the product is enabled
$products->addAttributeToFilter('status', 1);
// Add Name filter
$products->addAttributeToFilter('name', 'My Product Name');
// Limit the collection to 1 result
$products->setCurPage(1)->setPageSize(1);
// Load the collection
$products->load();
if ($products->getFirstItem()) {
$product = $products->getFirstItem();
echo $product->getName();
}
else {
echo 'No product exists with the name ' . $name;
}
The above code is a lot longer than the code we used to load by SKU, but hopefully you can see the power and flexibility of the Magento collection code. Line #17 is where the filter is added to filter by name, but the rest of the code is required to ensure that the product returned is a valid product.
If you are wondering what the SQL query the above generates, add the following line anywhere before line #23.
<?php
// Print out the SQL query generated by the collection object so far
echo $products->getSelect() . '<br/><br/>';
Load a Category by an Attribute
Load a category by an attribute is almost exactly the same. The reason for this is that both products and categories use Magento's EAV database structure and both extend from the same base classes, which provide the core collection functionality (as do the majority of Magento model's).
<?php
// Instantiate a category collection object
$categories = Mage::getResourceModel('catalog/categories_collection');
// Select which fields to load into the category
// * will load all fields but it is possible to pass an array of
// select fields to load
$categories->addAttributeToSelect('*');
// Ensure the category is active
$categories->addAttributeToFilter('is_active', 1);
// Add Name filter
$categories->addAttributeToFilter('name', 'My Category Name');
// Limit the collection to 1 result
$categories->setCurPage(1)->setPageSize(1);
// Load the collection
$categories->load();
if ($categories->getFirstItem()) {
$category = $categories->getFirstItem();
echo $category->getName();
}
else {
echo 'No category exists with the name ' . $name;
}
The main difference when working with categories is the resource model name (line #3) and the filter for the `is_active` attribute.
Hopefully you can see how flexible and powerful the Magento collection system is. I recommend that you print out the SQL query command for your collections so you can understand what Magento is doing in the background. Although Magento protects you from really needing to know this information, understanding it will make you a better developer and if you're like me, you'll find it interesting to disect the SQL!
PHP CMS Frameworks
November 10, 2013
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.
Browse topics
Stay updated
Get the latest PHP & CMS tutorials straight to your inbox. No spam, just code.
Trending posts
- Steps to create a Contact Form in Symfony With SwiftMailer
- Drupal 7 - Create your custom Hello World module
- CIBB - Basic Forum With Codeigniter and Twitter Bootstrap
- Create Ajax Pagination in CodeIgniter - Step by step procedure
- A step by step procedure to develop wordpress plugin
- Steps to use Wordpress like pager in Drupal
- Create Front End Component in Joomla - Step by step procedure
- Unleashing the Power of Drupal 10: Advantages and Features
- Introducing Drupal 10: The Next Evolution in Web Development
- Magento - Steps to add Custom Tabs to the Product Admin