CodeIgniter global variable - php

I am using $data in all my views $this->load->view('my_view', $data);
I have also autoload a Controller following this guide Extending Core Controller
But I want to make $data global because in views there is a sidebar which is constant for whole project and displays info fetched through db in autoloaded controller
Currently I have to manually write $data['todo'] for each and fetch info from autoloaded model.
Thank You.

1: Create MY_Controller in application/libraries with following:
class MY_Controller extends Controller {
var $data;
//constructor function
}
2: Replace Controller to MY_Controller in all your controller files and load views with $this->data
class Contact extends Controller { //to.. }
class Contact extends MY_Controller {
$this->load->view('contact_view', $this->data);
}
this way you can perform default functions that are applicable for whole site in MY_Controller like loading settings.

I ran into a similar problem earlier today. I found that an easier way, rather than globals, was to use constants. You can define a constants file that will load from your index.php file:
// Include additional constants
$defines_file = 'includes/defines.php';
if (file_exists($defines_file))
{
require_once($defines_file);
}
Then you can add your constants to the defines.php file:
define(MY_CONSTANT,'my constant info');
This way they will be available in any file throughout the system either directly: echo MY_CONSTANT; or you can assign them to variables.
I decided this way would be easier for me as I would only have 1 location to go to when/if I needed to change the constants.
More: http://codeigniter.com/forums/viewthread/56981/#280205

I used a helper function to call a global function!
eg.
function get_user($userid){
$CI =& get_instance();
$query = $CI->db->get_where('users', array('id' => $userid), 1, 0);
foreach ($query->result() as $row){
// Return a object with userdata!
return $row;
}
}
Now I have access to my userdata everywhere..

Rather than making the view data global, I'd recommend using HMVC to build a module to produce this sidebar view. HMVC is a nice clean way of coding partial views.

Related

in codeigniter Non-existent class: Commonlib is library file

here is my library file
libraray file name Commonlib
<?php
class Commonlib extends CI_Controller
{
public function __construct()
{
parent::__construct();
$ci=& get_instance();
$ci->load->database();
}
function getcountries()
{
return $ci->db->get("countries")->result();
}
}
in config file
$autoload['libraries'] = array('database','Commonlib');
here is my view
$a = new Commonlib();
$results=$a->getcountries();
foreach ($results as $row) {
// country_id
echo ''.$row->country .'<br>';
}
show this error Non-existent class:
where is trouble ? how to solve it ?
The problem is here of naming convention. Because Class names and file names must match.
<?php
class Commonlib {
public function __construct() {
parent::__construct();
$ci=& get_instance();
$ci->load->database();
}
function getcountries(){
return $ci->db->get("countries")->result();
}
}
In view
$a = new Commonlib();
$results=$a->getcountries();
foreach ($results as $row)
{ // country_id
echo ''.$row->country .'<br>';
}
Library name should be like this CI_Commonlib ... Please try.
go To your library and change it with this code.
<?php
class your_library_Name {
function getcountries(){
return $ci->db->get("countries")->result();
}
}
and this is how to call it
$rec= $this->your_library_Name->getcountries();
You can do any of a few things.
By default most people will just drop their library into system/libraries, and load it with either with the autoloader, or $this->load->library(). If you do this, you must prefix your class name with CI_ so that CodeIgniter will recognize it, since the system folder is intended for stock files. In your case, you would need:
class CI_Commonlib extends CI_Controller
{
}
This works, but it mixes your custom code into CodeIgniter system files, which can become very messy when you want to upgrade your installation.
My recommendation is to create a separate folder for your custom files, and then add that path to your loader object. You will not need to make any changes to the code if you move your Commonlib object to application/libraries/Commonlib.php.
People will often add custom objects to system when they want to share files between multiple CodeIgniter installations. Multiple applications can share the same BASEPATH, so it makes sense to put your code where the shared directory already exists.
The problem with this is the same issue with an upgrade path, where custom objects mix with stock code, and may get confusing. In this case defining your own shared folder can be very helpful. CodeIgniter lets you do that with $this->load->add_package_path() You can move your shared code into custom/libraries and be off to the races. In that case, you can update your controller (not view) accordingly.
https://www.codeigniter.com/user_guide/libraries/loader.html
$this->load->add_package_path('custom/libraries');
$this->load->library('commonlib');

Make things available in any view file Laravel

I have a question about making some elements available in any view file
Lets say im building a webshop and on every page i will be having my sidebar, shoppingcart, user greeting in the top.
How can i make these things available in all my view files?
I could make a class, lets say class Frontend
I could do something like this:
class Frontend {
static $me;
public function get(){
if(!self::$me){
self::$me = new self();
}
return self::$me;
}
private function getShoppingCart(){
// do things
}
public function getData(){
return array(
'Username' => User::find(1)->UserName,
'Cart' => $this->getShoppingCart()
);
}
}
Now in my controller i could pass this Frontend object into the view
View::make('file.view')->with(array('data' => Frontend::get()->getData()));
But this way i will end up with a god class containing way too much stuff and in every controller method i would have to pass these data, which is not relevant to the controller method
Is there a way in Laravel that makes specific data available across all view files?
Thanks!
Use share:
View::share('name', 'Steve');
as per http://laravel.com/docs/responses#views
To keep everything clean, every part of the page should be its own *.blade.php file which would be put together using a master template of sorts.
master.blade.php
#yield('includes.sidebar')
#yield('users.greeting')
#yield('store.shoppingcart')
Then you can use view composers so that each time these views are loaded, the data you want is injected into them. I would probably either create a new file which would get autoloaded, or if you have service providers for the separate portions of your app that these views would use, it would also go great in there.
View::composer('users.greeting', function($view)
{
$view->with('user', Auth::user());
});
In this case, it would make the user model available inside your view. This makes it very easy to manage which data gets injected into your views.
You are close with your 'god class' idea.
Setting a $data variable in a basecontroller has helped me with similar issues
class BaseController extends Controller {
protected $data;
public function __construct() {
$this->data['Username'] = User::find(1)->UserName
$this->data['Cart'] = $this->getShoppingCart()
}
}
class Frontend extends BaseController {
function someMethod(){
View::make('file.view', $this->data)
}
}

How to define a global variable(value) in codeIgniter

I simply do not mean how to define a global variable/constant in CodeIgniter.
Let me explain:
I have made a theme engine which is select-able from the current logged in user's control panel. This engine is not very complicated, but a simple folder. anyway, what I do across the application, is that I write one line of code to get the current theme selected by the user. I use a one line of code to get the name, and then store it in a variable:
$theme_name = $this->theme->get_theme_with_slash(false);
And then, I user $theme_name like this to get the proper view:
$this->load->view($theme_name.'result', $data);
And in all of my controllers that loads view I should repeat this process. What I need, is to call the function which gets the theme_name and store in the variable and then use the variable/session/function across the application. My approach currently is the helper's function which is a little less convenient compared to session/variable.
I got this from the manual and this what I have at the top of my config/config.php file: (i have a custom config set to paypal testing)
// HOW TO USE - For example if there's $config['foo'] = 'bar';
// in the config
// using $this- >config->item('foo') will be 'bar'.
// example for my paypal testing:
$config['paypaltest']=0;
http://ellislab.com/codeigniter%20/user-guide/libraries/config.html
and how to access in a controller:
$paypaltest = $this->config->item('paypaltest');
Create A core controller, since your process requires logical operations then you need a method for that.
application/core/MY_Controller.php
class MY_Controller Extends CI_Controller
{
protected $default_theme = 'theme';
public function __construct()
{
parent::__construct();
}
public function get_theme()
{
//your code for selecting the current theme selected from
//the database
$theme_from_db = '';
return $theme_from_db == NULL ? $this->default_theme : $theme_from_db;
}
}
Your Controller must extend MY_Controller
application/controller/view.php
class view extends MY_Controller
{
public function index()
{
$this->load->view($this->get_theme().'result', $data);
}
}
in code igniter global constants can be defined in
config->constants.php
even you no need to load it,it automatically autoloaded by CI automatically.
In Codeigniter all constant is defined inside application/config/constant.php.
like: define("CONSTANTNAME","value");
Constant degined here is accessible throughout all pages, ie; controllers, models and views

Autoload function and get variables in codeIgniter

I have this question: how to load function in codeIgniter in every page and get data or variables from it to show in view?
I have many controllers and each one has many function. Each function load master view as a template and load its own view. Master view has dynamic data I push it from database.
So I need in master view to show some data from database automatically. How to do it?
You can use this. change it according to your
function index()
{
$data['list'] = $this->some_model->show_data();
$data1['content'] = $this->load->view('some_view',$data,true);
$this->load->view('template',$data1);
}
content is in your main template where u will pass your data to show in template
I am not sure what exactly you ask but if you want a function to be loaded automatically to any controller
then create a Mycontroller.php in application/core
class Mycontroller extends CI_Controller
{
function __construct()
{
parent::__construct();
// here goes your function
}
}
and then extend every controller you have to Mycontroller instead of CI_Controller
if you want to use your function inside views. use CI Helpers
Codeigniter Helpers
create your helper function
function get_data() {
// and use CI instance
$CI = & get_instance();
// now you can call your models, libraries. etc. in the helper
$data = $CI->your_model->your_model_funcion();
return $data;
}
and you can call your helper function in controllers, views, models. etc...
get_data();

Where do I put constants file for Codeigniter (PHP)?

I have a list of constants (I'm using them as an enum), some are define statements, and some are just global variables.
Where am I suppose to put them in the MVC framework so I can use them for both my model and my controller that needs to reference it?
I'd rather not stick it into config/constants.php since they shouldn't be called except for by this model and the controllers that use it.
Edit 1: Clarification
To be more specific, I have my message_model model and it has a bunch of constants that I need that are stored in message_model_constants.php. Where should I put message_model_constants.php and is there a way to have it automatically included by the controller that loads message_model when message_model is not (and I don't want it to be) auto-loaded.
Edit 2:
I really don't want to have the constants auto-loaded except for when I use the model
Go to application/config/constants.php and define your constant their and you can use your constants on Model-View-Controller of CI not include "Helper" and "Library"
But in your case I prefer you to create a php file that has your constants and rename it to something like my_constants_helper.php.
In your model or controller __construct just
$this->load->helper('my_constants');
And hooray you can access them =)
You can choose to load a particular config file when you load a particular model in the controller. For instance in your file:
application/controllers/messages.php
You would use a line like this:
$this->config->load('messages');
If you include it at the top of your controller like this
function __construct() {
$this->config->load('messages');
$this->load->model('message_model');
}
Then all of those constants will be available to all the functions and methods in the given controller. You then call each config constant like:
$this->config->item('item name')
And you can name protected $variables; in the construct as well for shorter syntax.
If you are using these config constants and the message model in multiple different controllers you may want make a "Library" file that then loads both the config and the model and declares all variables there.
extending Brennan Novak answer, you can simplify your code by loading your config file in the model constructor. That way, you only have to load the model in your controllers and everything else is done automatically.
Model
class Message_model extends Model {
function __construct()
{
parent::Model();
$this->load->config('message_model_constants');
}
...
}
Controller
class Some_controller extends Controller {
function __construct()
{
parent::Controller();
$this->load->model('message_model');
}
...
}
As already stated, your config files should be application/config/message_model_constants.php
For global configs, add to the config/config.php or create a config/application.php and then load the config, then the item.
$this->config->load('application'); // or autoload this - $autoload['config'] = array('application');
$this->config->item('item name');
Have you considered just adding your constants to your Message_Model Class? You'll then reference them by self::ConstantName inside the Class and Message_Model::ConstantName outside the class. This would also prevent name space collision.

Categories