How to load helper from model in CodeIgniter? - php

I want to load some helper in a model. How to do this? Tried to use:
${get_parent_class($this)}->load->helper ('text');
But still getting an error
Fatal error: Call to a member function helper() on a non-object

GSto answered $this->load->helper('helpername') but if you are in a model's method, $this simply refers to that model's (class) instance and not to CI global. That won't work!
Instead you need to load the CI global and then load the helper:
// PHP 4
// $ci =& get_instance();
// PHP 5
$ci = get_instance();
$ci->load->helper('text');

You are not need to load helper in a model.Just load helper in a controller and use function in a model as well as we normally use helper function in a controller

$this->load->helper('helpername')

I think CI doesnt check for helper duplication ... CI herlpers are procedural files , you might include ur helper twice if ur controller has the same helper loaded as ur model (that is loaded in that controller). Maybe do a library instead...
I can see i get negative votes w/o any comments ... by checking loader class from core CI u can see helpers method isnt checking if the helper has been loaded before (it isn't included in is_loaded() array like most classes that are loaded through load factory class) ... I dont recommend anyway to load helpers in both models and controllers ... for ex i made a helper for output encoding that i use in controllers (before i pass data to the view) . It would be very bad if i change the view state twice ...

Related

Is there a difference between the method of helper and library are called upon in code igniter?

I am getting little bit confused, the way the methods of library and helper are used in code igniter. I am still learning code igniter.
CONTROLLER
function index(){
$this->load->helper('text');
$this->load->library('auth'); //custom library
$data['string'] = 'this is sample ..... this is sample';
$this->load->view('article', $data);
}
VIEW
<?php
if(is_logged_in()){ //is_logged_in() is the method from the library, 'auth'
echo 'You are logged in';
}
<p><?php echo word_limiter($string, 10); ?></p> <!--word_limiter() is the method from the helper, 'text' -->
In the above view file, the helper method word_limiter() works fine. But the method is_logged_in() does not work. But if I do ($this->auth->is_logged_in()), it will work.
But why the method from helper i.e. word_limiter() does not have to be written like this ($this->text->word_limiter()).
Is there a difference between the method of helper and library are called upon ?
A CodeIgniter helper is a set of related functions (Common functions) which you could use them within Models, Views, Controllers,.. everywhere.
Once you load (include) that file, you can get access to the functions.
But a Library is a class, which you need to make an instance of the class (by $this->load->library()). And you'll need to use the object $this->... to call the methods.
As a thumb rule: A library is used in object oriented context (Controller, ...), while a helper is more suitable to be used within the Views (non object oriented).
CI Helper may or may not have class
But Library must have class representation.
Refer this SO Answer
CodeIgniter: Decision making for creating of library & helper in CodeIgniter

How to load function from library on page load using codeigniter

I am doing my project using codeigniter
I want load a function when the page loads. i tried to give the function in __construct() but i need to call the function at every page.
So i want to call the function which is in library without calling from __construct()
Can anyone give me the solution for my problem
Take a look into the hooks. You can configure a function or a method of a class to be executed in various places in the life cycle of every request, depending in your needs.
If you need the controller instance for your functionality (the $this in most contexts) you probably need the post_controller_constructor one, and use the get_instance() to get a hold of the controller instance inside of the hook, to load in libraries or call models and such.
An other way could be that you extend the CI_Controller class with a MY_Controller class, place it under application/core/MY_Controller.php and move your code inside that classes __construct and use the MY_Controller as the base class of your regular controllers, as described the Creating Core System Classes page.
Add a library in autoload, then in that library file use __construct to call your function.

Codeigniter/OOP: after loading a custom class, I can't load a model

I’m learning CI coming from a non MVC OOP in-house framework, so I’m still confused on a bunch of things, I don’t always understand what is normal OO programming VS. things that done the code igniter way. Anyway I’ll try to explain my problem:
I have one controller, called Admin which extends CI_Controller.
I made a class (let’s say custom class meaning is something I made not part od CI) I put that class in the library folder, that class extends CI_Controller as well (that extension allowed me to have load method and some other CI methods).
From my Admin controller, I’m loading my custom class (named “ComponiPannello” since I’m italian ), this way:
$parameters = array('baseUrl' => $this->baseUrl);
$this->load->library('ComponiPannello', $parameters);
everything works perfectly my “ComponiPannello” does hits job and returns something I need for my Admin view.
Now I wanted to load a model right after that class, because I need to pass more info to the Admin view, those info are stored in the DB, I have a specific model to pull those extra info, so I added a few lines and the code looks as follow:
$parameters = array('baseUrl' => $this->baseUrl);
$this->load->library('ComponiPannello', $parameters);
$setup = $this->componipannello->return_data();
$this->data = array_merge($this->data, $setup);
$this->load->model('categories_model');
$this->data['categories'] = $this->categories_model->get_categories();
were $this->data is what I’m passing to the Admin’s view.
Few more info:
as I said both Admin controller and my custom class ComponiPannello extends CI_Controller
in ComponiPannello I have this constructor:
function _construct($params) {
parent::_construct();
$this->load->library('session');
$this->baseUrl = $params['baseUrl'];
}
if I move the $this->load->model part before the $this->load->library I get no errors everything works and returns the correct data, but I would like to learn what I’m doing.
if I keep it as I have it the error I get is the following:
Fatal error: Call to a member function get_categories() on a non-object in ... on line ...
I hope I was able to explain my issue in a way that is clear enough for you to help me, thanks in advance for the time spent.
Luke
Your problem is probably coming about because you are loading another controller as a library, when in fact, it is not a library.
You can load libraries, helpers, etc from a library like this:
$CI =& get_instance();
From within your library, instead of $this->load->helper() to load a helper you would now use $CI->load->helper().
More info on this is available in the CI documentation: http://ellislab.com/codeigniter/user-guide/general/creating_libraries.html
Whay u use database object in ur library?
Utilizing CodeIgniter Resources within Your Library.
To access CodeIgniter's native resources within your library use the get_instance() function. This function returns the CodeIgniter super object.
Normally from within your controller functions you will call any of the available CodeIgniter functions using the $this construct:
$this->load->helper('url');
$this->load->library('session');
$this->config->item('base_url');
etc.
$this, however, only works directly within your controllers, your models, or your views. If you would like to use CodeIgniter's classes from within your own custom classes you can do so as follows:
First, assign the CodeIgniter object to a variable:
$CI =& get_instance();
$CI->load->helper('url');
$CI->load->library('session');
$CI->config->item('base_url');
etc.

CodeIgniter Controller Constructor

I'm very new to codeigniter ,
I wanted to know what is the meaning of a constructor in a controller . I saw the following code in a codeigniter tutorial -
class upload extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper(form);
}
// rest of the class...
My question is when is the constructor invoked - is it called every time the controller serves a request (e.g the controller class is instantiated for each request it receives?)
Well, that's a more general PHP question. Anyway, yes, the magic method __construct() is called (automatically) upon each instantiation of the class, as you can see in the manual: http://www.php.net/manual/en/language.oop5.decon.php
Usually, in CI is not necessary to call a constructor, unless you actually want one. In the example you posted, the code loads the helper on every instantiation of the class - which is the same as loading the helper in every method, just saves a lot of typing and ensures it's not forgotten. You can alternatively put the library/helper/model you want to have alywas loaded in the respective autoload array in config/autoload.php (check "autoloading" in CI's manual)
Once you define a constructor in your child Controller you're compelled to call the parent constructor (of the mail CI_Controller class), because there is where the main CI object is created and all the classes are loaded, and you need those in your child controller too; if fail to do so your child class will construct separately and won't inherit.
I hope I made myself clear, english is not my mothertongue :)
the constructor is magic Literally its called a magic method.
what makes the constructor cool is that it will do things for you BEFORE any of the methods. So if you have an admin class, and someone should be logged in in order to access it - you can check for login in the constructor and bounce them out if they are not authorized.
in the constructor you can load the models, libraries, helpers, etc that your class needs, and they will be available for any method in the class.
you can load in variables that are used by methods. this is really useful for models.
Don't use _construct() function in latest apache & codeigniter
Use helperlin in index() function
That's a general question. Constructor is a function that is automatically called when instantiated. this function helps us to intialize the things that we are going to need frequently in our code like when we have to load the models of helpers like form e.t.c.
$this->load->model('Model_name');
now when you write this line in your constructor you don't need to load this model again and again in your methods of that class.

access model from view in codeigniter?

can anyone tell me how do i access model from view in codeigniter?
Load a model on the controller
$this->load->model('yourmodel');
Assign this model to a var like this
$data['model_obj'] = $this->yourmodel;
and assign this data array to your view template
Use $model_obj object on the view template for calling model methods
$model_obj->some_method()
Hope this helps ...
See the thread:
View Calling a Model
By the way why do you need to access the model from the view, you can send the model data to the view from the controller too which is the usual and better approach.
As a good note, keep your processing logic out of the view, you should use controller instead.
CodeIgniter's $this->load->model() returns absolutely nothing. Look at it: system/libraries/Loader.php.
This will output absolutely nothing:
$model = $this->load->model('table');
print_r($model);
And this next example will give you the fatal error Call to a member function some_func() on a non-object:
$model = $this->load->model('table');
$model->some_func();
It doesn't matter whether that function even exists, $model is not an object.
The thing to do is have a method in your model that returns data, then call that function and pass the results to your view file:
$this->load->model('table');
$data = $this->table->some_func();
$this->load->view('view', $data);
PS: How is the only answer you've accepted the absolute wrong thing to do?
You can use following code:
$ci = &get_instance();
$ci->load->model('your_model');
$ci->your_model->your_function();
Note: You have to call your model in your controller. Its working fine
In cases when you want to access a model function from within a shared view , you don't have to load the needed model in every controller that will call that view. you can load the model inside the view itself by using the following code :
$ci =&get_instance();
$ci->load->model(model_name);
$ci->model_name->function_name();
in older versions of codeigniter the following code used to work :
$this->load->model('model_name');
model_name::function();
but when tested on CI 3.1.9 it throw the following error
Message: Undefined property: CI_Loader::$model_name_model
Note: I use this technique in template views (sidebar, menus ...etc) which is not used everywhere in my application , if you want to access a model from anywhere in your application considre loading this model globally by adding it to the autoload array in application/config/autoload.php
Since $model is not an object, you can make a call to the model "table" using "::" scope resolution operator, which can call the function of the class itself without any object instance.
$this->load->model('table');
table::some_funct();
Note: you also need to make the function "some_funct" static inside your model "table".
Hey. You can access from view to models the same mode as you access on its controller. Remember that the view access to models that import its controller.
in the original UML I've seem for MVC architecture, view calls methods in model..
http://www.as3dp.com/wp-content/uploads/2010/02/mvc_pope_krasner.png
..but in practice with PHP apps, because there is no persistence to track state changes in objects between requests (or at least not efficiently), I find it better to keep all model method calls in controller and pass the result to view if possible.
you can add your model's name to config -> autoload model
$autoload['model'] = array('model_name');
this success for me
You can access basicly a method from view in codeingiter.
public function index()
{
$this->load->model('persons');
$data['mydata'] = $this->persons->getAllSessionData();
$this->load->view('test_page', $data);
}
in view
print_r ($mydata);
my function returned an array.

Categories