how to deal with configuration file in CakePHP

R4D3K picture R4D3K · Sep 4, 2012 · Viewed 9.3k times · Source

I know that in folder config are file called core.php which I can configure application options as a debug mode, session, cache etc.

But I want do configure file for my application. I want for example configure how many post can be displayed in main page, thubnails size etc.

I think that the best place in config folder but where and when parse thos file in application (bootstrap, AppController another mechanism ?) and what is the best extension .ini or PHP array (for performance reason too). What is the best practice to do this ?

Answer

Arun Jain picture Arun Jain · Sep 5, 2012

DEFINE OWN CONSTANT FILE

Create a file lets suppose 'site_constants.php' containing some constant variables in app/Config folder. Define the following constants into it:

<?php    
define('HTTP_HOST', "http://" . $_SERVER['HTTP_HOST'].'/');
if(HTTP_HOST == 'localhost' || HTTP_HOST == '127.0.0.1')
{
     define('SITE_URL', HTTP_HOST.'app_folder_name/');
}
else
{
     define('SITE_URL', HTTP_HOST);
}

Include it in app/Config/bootstrap.php

require_once('site_constants.php');

Now you can use it anywhere into your website. And this is also a dynamic.

DEFINE OWN CONFIGURATION FILE

Create a file lets suppose 'my_config.php' containing some constant variables in app/Config folder. Define the constant in the following way:

<?php
$config['PageConfig'] = array('PostPerPage' => 5, 'UserPerPage' => 15);

Then in your app/Controller/AppController.php write the following line in beforeFilter() method:

function beforeFilter()
{ 
     Configure::load('my_config');        
}

Now in your controller's method, where you want to access the page number to be listed in your pagination list. You can use it by following code:

$page_config = Configure :: read('PageConfig');   
$user_per_page = $page_config['UserPerPage']; 
//or
$post_per_page = $page_config['PostPerPage']; 

This might looks long process to handle this task, but once done, it will help you in many senses.

Here are the advantages:

  1. you can easily define some more constants (like any file path etc).
  2. you can put all your ajax code into external JS files.
  3. you can directly deploy it onto any server without changing in constants as well as work perfectly onto your localhost.
  4. following standard conventions etc.