Setting variable to be accessed by different methods within the class - php

I have a controller with different methods, but they all have to set a variable containing a list of items to be shown in a box in the view, I extract data from the DB and set $data['categories'].
Can I set it once and have it visible by all methods?

In addition to this, if you are only using $this->data to get the values into your views, instead of doing:
$this->data->something = 'whatever';
Then doing
$this->load->view('something', $this->data);
You can instead set it with:
$this->load->vars('something', 'whatever');
Then later on use the normal localized $data array (or whatever you like) as the variable will be globally available to all loaded view files.
I'm not suggesting either way is better, just letting you know how else it could be done. I personally use a mix of these methods. :-)

make it a property of the class
class Controller {
protected $data;
and use '$this' to access in in your methods:
class Controller {
function foo() {
$this->data etc...

Related

How to use global variables in codeigniter?

I am developing an application in codeigniter containing different modules e.g buyer, seller, public. All these modules use same header file. I want a global variable declared in buyer, seller and public controller so that when I load views of one module this variable should help customizing parts of header for seller depending upon its value. Same goes for buyer and public modules.
I want to ask what is the way to have a variable declared at controller scope and then use its value in its views. I have tried declaring and assigning its value in constructor but I get undefined variable error when loading the views. I also tried this way:
class Seller extends CI_Controller {
public $pagetype="seller";
public function __construct()
{
parent::__construct();
}
But I still get undefined variable error.
I can pass value of page type when loading view but I have to do that for each view, which is bad and cumbersome way because I have around 25-30 views in each controller.
Any help?
in your controller you can make data globally available in the view layer using this
$this->load->vars($data);
where $data is an array of key => values. you could put this in your constructor, or parent constructor
Consider making your own class - look into Singleton or Registry design patterns... but also read this: What is so bad about singletons?
you could assign the main CodeIgniter object to a variable and then use load->get_var($key) to get the view variable.
function something() {
$ci =& get_instance();
$myvar = $ci->load->get_var(‘myvar);
}

Design, repeated code - need some advice

I'll try to explain my situation as clear as I can.
I'm building a framework. Its system contains following directories:
1) Core - routing, main class (autoloading, configs, constants), requests
2) Helpers
3) Libraries
In index.php, I set all most important configuration variables such as the base url, or index file. I set them inside of the "main class".
These attributes are private, because I dont want anyone to change them during the request flow.
So the only point of access to these variables is from the "main class" methods.
Now, one of these private variables is $_base_url.
I want users to be able to access base_url from some better place however, like URL class (inside of the helper directory).
To achieve this, I have to create two methods - get_base_url() inside of the "main class", and get_base_url() inside of the url class, which will do something like this:
class Url {
public static function get_base_url() {
return Main_Class::get_base_url();
}
}
My problem is - I have a couple of such variables which I'd like to call from different classes.
I will have a lot of repeated code.
The only solution I see is just setting these variables in different classes directly, but I'd like to have them centralized inside the main class.
How should I handle this?
You can create another class called variables (or whatever you prefer) then use static variables with that clase to be able to call them back and forth. Something like this:
<?php class Variables {
static $_base_url = "http://base_url";
} ?>
That way you can call your variables like this:
Variables::$_base_url;
To expand on your comment:
With inheritance you can have a situation where 2 classes have different values for the same $variable. In this example all instances will hold a different value for $_base_url;
class ParentClass {
protected $_base_url = "SOME VALUE";
}
class SubClassA extends ParentClass {
protected __construct() {
$this->_base_url = 'VALUE X';
}
}
class SubClassB extends ParentClass {
protected __construct() {
$this->_base_url = 'DIFFERENT VALUE THAN SubClassA';
}
}
Again, it depends on what you are trying to accomplish. If you want your variables act more like Settings or if you just want to have those variables within your instance.
Why you need a variable to be called from the classname, if the classes extends your MainClass then use parent::get_base_url();

When and How to make class variables with PHP?

Newbie question, i have variables inside my class method, do i have to make them class variables where i can access them using $this? If no, please explain when do i use or make a class variables?
private function is_valid_cookie()
{
$securedtoken = $this->input->cookie('securedtoken');
// Checks if the cookie is set
if (!empty($securedtoken)) {
// Checks if the cookie is in the database
$s = $this->db->escape($securedtoken);
$query = $this->db->query("SELECT cookie_variable FROM jb_login_cookies WHERE cookie_variable=$s");
if ($query->num_rows() != 0) {
// Now let us decrypt the cookie variables
$decoded = unserialize($this->encrypt->decode($securedtoken));
$this->login($decoded['username'], $decoded['password']);
return true;
} else {
return false;
}
} else {
return false;
}
}
as you guys can see, i have variables $securedtoken and $decoded = array(), i cant decide if i have to make them class variables and just access them with $this
I actually try to minimize use of class-level variables to cases where they are going to be common amongst multiple methods, or they are going to be referenced from code outside the class (either directly or via getters/setters). If the variable is just needed in local scope for a method, do not pollute the class with it.
You'll want to make class variables when you are trying to share those variables throughout different functions in the class. You'll then need different Access Modifiers (public, private, protected) for these properties depending on whether or not outside code can view them, child classes can view them, or nothing at all.
You do not have to make them instance variables. You can make them static variables too, or constant variables! You use a class variable to describe attributes of a class. ie what a class has.
Its important to get your terminology correct too. You are asking about making the variable and instance variable. A class variable (http://en.wikipedia.org/wiki/Class_variable) refers to a static variable
For your specific example if your two variables are only used in that function you should not make them instance variables. There is no reason to share them accross the class
On the other hand if you need to use them again in other methods or in other places than yes. you should.
Deciding what kind of variable you want and what kind of access is a design decision.
Good places to start are object oriented php overview. http://php.net/manual/en/language.oop5.php
And basic beginner tutorials
http://www.killerphp.com/tutorials/object-oriented-php/
You do, yes. You can declare class variables like this:
class Dog
{
protected $name = 'Spot';
public function getName()
{
return $this->name;
}
}
You can read more about properties (member variables) in the documentation.

Define variables outside the PHP class

I m using zend.
I want to define the below code outside the controller class & access in different Actions.
$user = new Zend_Session_Namespace('user');
$logInArray = array();
$logInArray['userId'] = $user->userid;
$logInArray['orgId'] = $user->authOrgId;
class VerifierController extends SystemadminController
{
public function indexAction()
{
// action body
print_r($logInArray);
}
}
But it does not print this array in index function on the other hand it show this array outside the class.
How it is possible.
Thanks.
To access a global variable from inside a method/function, you have to declare it as global, inside the method/function :
class VerifierController extends SystemadminController
{
public function indexAction()
{
global $logInArray;
// action body
print_r($logInArray);
}
}
In the manual, see the section about Variable scope.
Still, note that using global variables is not quite a good practice : in this case, your class is not independant anymore : it relies on the presence, and correct definition, of an external variable -- which is bad.
Maybe a solution would be to :
pass that variable as a parameter to the method ?
or pass it to the constructor of your class, and store it in a property ?
or add a method that will receive that variable, and store it in a property, if you cannot change the constructor ?
print_r($GLOBALS['logInArray']);
http://php.net/manual/en/reserved.variables.globals.php
You can store the user in many ways and access it in more clean manner. You can store it in Zend_Registry and then use Zend_Registry::get('user') where you need to retrieve the user. You can also store it as a parameter of request object, and then in a controller simply do $user = $this->_getParam('user');
If you need access to the user array in many controllers that inherit from the SystemadminController, what you can do is store it as a protected property of the SystemadminController (eg. protected $_user). Then all you need to do in child controllers is access $this->_user.

Passing parameters to controller's constructor

I have a controller which has several methods which should all share common informations. Let's say my URI format is like this:
http://server/users/id/admin/index
http://server/users/id/admin/new
http://server/users/id/admin/list
http://server/users/id/admin/delete
I need to retrieve some informations from the database for id and have them available for all methods instead of writing a line in each of them to call the model. How can I do this?
class users extends Controller {
private $mydata = array();
function users()
{
parent::Controller();
....
$this->mydata = $this->model->get_stuff($this->uri->segment(2));
}
function index()
{
$this->mydata; //hello data!
}
Here I simply hardcoded the array (which probably is a really bad idea). Nevertheless you can store the data in a codeigniter session if you need to. Codeigniter can store this data in a cookie (if it's total is less than 4kb) otherwise you can store bigger blobs of data in the database (see the docs on how to do this).
See: http://codeigniter.com/user_guide/libraries/sessions.html
Subsection: Saving Session Data to a Database
Here's some session exercise:
$this->session->set_userdata('mydata', $mydata);
....
$mydata = $this->session->userdata('mydata');
If this cannot be solved from CodeIgniters Hook mechanism, you could override the constructor method in your controller and call your own. Judging from their SVN repository you'd probably would do something like
class YourController extends Controller
{
function YourController()
{
parent::Controller();
$this->_preDispatch();
}
function _preDispatch()
{
// any code you want to run before the controller action is called
}
Might be that the call to preDispatch has to be before the call to parent. Just try it and see if it works. I didnt know they still use PHP4 syntax. Ugh :(
Based on your url structure, and the fact that codeignitor uses a MVC pattern, I'm assuming you're using mod_rewrite to format the url path into a query string for index.php. If this is the case, the value of "id" should be available at $_REQUEST['id'] at any point in the execution of the script...

Categories