Define custom variable in config.php and access it in view - codeigniter

I have defined image_path in config.php and now need to access this variable in views like we use base_url().
Hos is it possible?

You would need to extend the url_helper. See the "Extending Helpers" section in the documentation.
In short, create a file name MY_url_helper.php in your application/helpers folder. (Assuming $config['subclass_prefix'] = 'MY_', in your config file.)
Add the following method.
if ( ! function_exists('image_path'))
{
function image_path()
{
$CI =& get_instance();
return $CI->config->item('image_path');
}
}
This should do the trick.

Use constants.php, that's what it's for, this is out of my constants.php for image paths.
/*Constant paths*/
define('LOGO_PATH',APPPATH.'assets/images/manulogos/');
define('PROD_IMAGE_PATH',APPPATH.'../assets/images/prod_images/');
Then you just call the constant where you need it.
$imageName = $this->doUpload($control,PROD_IMAGE_PATH,$image,'all')

Related

How to get $config['imgURL_Path'] value from CodeIgniter's file config.php NOT from CI controller?

I want to get some constants, defined in CodeIgnitor in /application/config/config.php, but when i am outside CI controller. For example, i have a file that generates image thumbs or something else, that is outside CodeIgniter mvc framework. Cause the file /application/config/config.php has a string:
defined('BASEPATH') OR exit('No direct script access allowed');
i can't just do something like :
include '/application/config/config.php';
$imgPath = $config['imgURL_Path'];
I tried to add this strings, but no result:
if (defined('STDIN'))
{
chdir(dirname(__FILE__));
}
if (($_temp = realpath($system_path)) !== FALSE)
{
$system_path = $_temp.'/';
}
else
{
// Ensure there's a trailing slash
$system_path = rtrim($system_path, '/').'/';
}
// Is the system path correct?
if ( ! is_dir($system_path))
{
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: '.pathinfo(__FILE__, PATHINFO_BASENAME);
exit(3); // EXIT_CONFIG
}
define('BASEPATH', str_replace('\\', '/', $system_path));
include '/application/config/config.php';
$imgPath = $config['imgURL_Path'];
i also tried to make a file ci.php with this content:
<?php
// file: ci.php
ob_start();
require_once '../index.php';
ob_get_clean();
return $CI;
?>
and use it like:
$CI = require_once 'ci.php';
$imgPath = $CI->config->item('imgURL_Path');
but also no luck. What can be the solution?
If you want an URL_path or a variable that can be accessed anywhere, you can use helper.
1 Create a file in folder helpers, let's say you named it myvariable_helper.php //make sure you add '_helper' before the .php.
2 Open autoload in config folder, then search for $autoload['helper']
, insert your newly created helper there like this: $autoload['helper'] = array(url, myvariable)
3 Save the autoload, then open myvariable_helper.php, and add a function. Let's say you add an URL to a function like this:
<?php
function img_path()
{
$imgURL_Path = 'www.your_domain.com/image/upload';
return $imgURL_Path;
}
4 Call the function anywhere (even outside your MVC folder), using the function name, for example:
public function index()
{
$data['url'] = img_path(); //assign the variable using return value (which is 'www.your_domain.com/image/upload')
$this->load->view('Your_View', $data); //just for example
}
Note:
This helper can't be accessed from browser (like your model folder), so it's safe

Is it possible to call a codeigniter library inside another library file?

I want to call a function in a library inside another library which is written by me. Is it possible to do this in codeigniter? If so, can anyone explain how to do that?
You could do;
$CI =& get_instance();
$CI->load->library('your_library');
$CI->your_library->do_something();
Typically, you reference the Codeigniter object (the current controller, technically) by using get_instance(). Often you'll want to assign it to a property of your library, like this:
class My_Library {
private $CI;
function __construct()
{
// Assign by reference with "&" so we don't create a copy
$this->CI = &get_instance();
}
function do()
{
$var = $this->CI->my_other_library->get();
// etc.
}
}
Just make sure the other library is loaded or in your config/autoload.php.

Global Variables in CodeIgniter not Working

I want to generate global variables in CodeIgniter by creating my own library and config file. This is what I wrote ini my library file, let's say globalvars.php. I put it in /application/libraries.
class Globalvars{
function __construct($config = array())
{
foreach ($config as $key => $value) {
$data[$key] = $value;
}
$CI =& get_instance();
$CI->load->library('session');
$CI->load->vars($data);
}
}
I want the user id stored in the session to be available in global variable, so I wrote this in my config file. It's named also globalvars.php. It's in /application/config directory.
$config['user']=$this->session->userdata('id');
I then test to see if it's working by write it in my controller this way.
echo $data['user'];
But I get this error in the browser
Message: Undefined property: CI_Loader::$session
Filename: config/globalvars.php
It seems that the session functions is not defined yet. How can I get it work? What have I missed here? Any help would be appreciated.
You cannot use the session library in config file.
The config files are loaded before any libraries, so $this->session is undefined.
The config.php has to be loaded in order for the Session class to even be initialized, as it reads settings from that file.
A lot of issues with this type of thing (setting some "global" data) can be resolved using a base controller, and extending it in your controllers.
// core/MY_Controller.php
MY_Controller extends CI_Controller {
function __construct()
{
parent::__construct(); // Now the Session class should be loaded
// set config items here
}
}
"Normal" controllers will now extend MY_Controller to take advantage of this.
See: http://codeigniter.com/user_guide/general/core_classes.html for more details.
In addition, when you load->vars(), they are available to the view layer only, it does not create a global variable called $data as you seem to be trying to access. If you do this:
$this->load->vars(array('user' => '1'));
You would access it in a file loaded by $this->load->view() like this:
echo $user; // outputs "1"
See: http://codeigniter.com/user_guide/libraries/loader.html
$this->load->vars($array)
This function takes an associative array as input and generates
variables using the PHP extract function. This function produces the
same result as using the second parameter of the $this->load->view()
function above. The reason you might want to use this function
independently is if you would like to set some global variables in the
constructor of your controller and have them become available in any
view file loaded from any function. You can have multiple calls to
this function. The data get cached and merged into one array for
conversion to variables.
I will say that as an experienced Codeigniter user, the concept of a "global vars" class is a bit wonky and probably unnecessary, especially when it's already so easy to get and set config items. You could definitely run into some confusing issues and variable name conflicts with this method (pre-loading lots of view variables on every request).

$this->load->db(); initialize in class constructor?

I am putting this code in the constructor for a model class, based on teh tutorial for CI, it states that if you put it there, the database connection can be used globally within that class afterwards. For some reason it's not working and the application crashes at that part of the code. My database configuration is fine since when i put it in the controller i'm able to get db info fine.
Are you doing that before or after the parent class's constructor?
public function __construct()
{
// placing it here fails: $this has no `load` property yet.
// $this->load->database(); <!-- NO WAY JOSÉ!
parent::__construct();
// placing it here should work as the parent class has added that property
// during it's own constructor
$this->load->database();
}
On the other hand, you could be even more explicit:
public function __construct()
{
// Doesn't matter where this goes:
// grab the controller directly
$CI =& get_instance(); // & is not strictly necessary, but still...
// force the loader to load the database.
$CI->load->database();
// directly assign it.
$this->db = $CI->db;
// continue on your merry way
parent::__construct();
}
I believe the explicit solution solved a number of problems in a PHP 4 project once, but it is technically overkill.
you dont need to initialize that . better configure it into
application - config - autoload.php file like this
$autoload['libraries'] = array('database');
The line of code to load the database object is:
$this->load->database();
The database object is then referenced with the name db like so:
$this->db->method_name();
As pointed out by the previous post, if you are going to use the database across multiple models, you should have the library autoloaded in your autoload.php config file.

magento - create a global function

I want to create a function that can be accessed by all *.phtml files. Where should i place this function in the magento framework?
For down and dirty things, you can always define it in index.php. for example, I always put this function there:
function dumpit($obj)
{
print '<pre>';
print_r($obj);
print '</pre>';
}
Then you can quickly call this routine from anywhere, without having to remember all the other overhead function names to get at the helper.
You should create a module and a helper class in that module (Usually MyCompany_Mymodule_Helper_Data by default). Then, add your function to that helper class. You can get to that function in your PHTML like this:
Mage::helper("mymodule")->someFunction();
Hope that helps!
Thanks,
Joe
C:\wamp\www\mydirectory\app\code\core\Mage\Page\Helper\Data.php is my path. I used print_r function as the pr() function.
Put it in Data.php as below.
class Mage_Page_Helper_Data extends Mage_Core_Helper_Abstract
{
function pr($data)
{
echo "<pre>";
print_r($data);
echo "</pre>";
}
}
where page is mymodule.
Call it from any .phtml file with
Mage::helper("page")->pr($abcd);
Hope it helps.
For anyone who's interested I put together a short tutorial on how create a global function in Magento : http://joe-riggs.com/blog/2011/06/create-global-function-in-magento/

Resources