I'm writing a helper in CodeIgniter that I need to reuse in several controllers. The initial data loaded in the view rendered by the helper can vary depending on which controller uses the helper.
I'm trying this:
$controller = $CI->router->fetch_class();
$init = $CI->$controller->get_initial_data($id);
but getting
Call to a member function get_initial_data() on a non-object
When I view the variable contents with:
print_r($controller);
I see the name of the correct controller. Problem seems to be with $CI->$controller. Any ideas on how I can use the variable as the controller reference?
You can't access controller methods from anywhere else but from inside the controller itself. So, there is no way for the helper to call the get_initial_data method.
What you want to do is have the controller call its own get_initial_data method and pass the result as a parameter to the helper function.
For example (in your controller):
$data = $this->get_initial_data($id);
my_helper_function($data);
Try using
$CI->{$controller}->get_initial_data($id);
Related
I created a function like e.g. getAllCitiesOfLocations(). This functions delivers me an aggregation of cities. I want to have this function reusable like e.g. for the index function of the ServiceController. Inside the index function, I want to call the function getAllCitiesOfLocations() to fetch the information and later on deliver it to the view.
However, I red, that it is not proper style to call a function from another controller. Furthermore, I red, that I should create a helper class. Unfortunately, when I search for information how to create a helper class, I only find information about creating helper classes for the views. Can you tell me
1.) Where I should put the function, that should be called by different controllers if needed, and
2.) How I can call the function later on when it is not inside the same controller?
public function getAllCitiesOfLocations(){
$cities = DB::table('locations')
->select('city')
->groupBy('city')
->get();
return $cities;
}
You can use helper class like this
namespace App\Services;
class Helper {
public static function getAllCitiesOfLocations(){
// Code goes here
}
}
I usually store it inside app/services folder, but you can have it anywhere you like. Then in your controllers, you can access them like this:
App\Services\Helper::getAllCitiesOfLocations();
You can also let laravel autoload this class for you by adding it to your aliases array found in config/app.php
'Helper' => App\Services\Helper::class
Then when calling methods from your Helper class, you simply
Helper::getAllCitiesOfLocations();
This kind of function would belong in a model, not a controller. Generally if its dealing with the database, you put things in models.
What you want to do is have a Model. You can then use that Model in any controller you want to.
Please read https://requiremind.github.io/a-most-simple-php-mvc-beginners-tutorial/ to start working in MVC model.
I am a Java developer (I often used Spring MVC to develop MVC web app in Java) with a very litle knowledge of PHP and I have to work on a PHP project that use CodeIgniter 2.1.3.
So I have some doubts about how controller works in CodeIgniter.
1) In Spring MVC I have a controller class with some annoted method, each method handle a specific HTTP Request (the annotation defines the URL handled by the method) and return the name of the view that have to be shown.
Reading the official documentation of CodeIgniter it seems me that the logic of this framework is pretty different: https://www.codeigniter.com/userguide3/general/controllers.html#what-is-a-controller
So it seems to understand that in CodeIgniter is a class that handle a single URL of the application having the same name of the class name. Is it correct?
So I have this class:
class garanzieValoreFlex extends CI_Controller {
.....................................................
.....................................................
.....................................................
function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library(array('form_validation','session'));
}
public function reset() {
$this->session->unset_userdata("datiPreventivo");
$this->load->view('garanziavalore/garanzie_valore_questionario_bootstrap',array());
}
public function index() {
$this->load->model('Direct');
$flagDeroga = "true" ;
$this->session->userdata("flagDeroga");
$data = $this->session->userdata("datiPreventivo");
$this->load->model('GaranzieValoreFlexModel');
$data = $this->session->userdata("datiPreventivo");
$this->load->model('GaranzieValoreFlexModel');
$this->load->view('garanziavalore/index_bootstrap',$data);
}
public function back() {
$this->load->model('Direct');
$flagDeroga = "true" ;
$this->session->userdata("flagDeroga");
$data = $this->session->userdata("datiPreventivo");
$this->load->model('GaranzieValoreFlexModel');
//$this->load->view('garanziavalore/garanzie_valore_questionario_bootstrap',$data);
$this->load->view('garanziavalore/index_tornaIndietro_bootstrap',$data);
}
.....................................................
.....................................................
.....................................................
}
So, from what I have understand, basically this controller handle only the HTTP Request toward the URL: http://MYURL/garanzieValoreFlex.
So from what I have understand the method performed when I access to the previous URL is the index() that by this line:
$this->load->view('garanziavalore/index_bootstrap',$data);
show the garanziavalore/index_bootstrap.php page that I found into the views directory of my prohect (is it a standard that have to be into the views directory?)
Is it my reasoning correct?
If yes I am loading the view passing to id also the $data variable that I think is the model containing the data that can be shown in the page, this variable is retrieved by:
$data = $this->session->userdata("datiPreventivo");
What exactly does this line?
The last doubt is related the other back() method that I have found in the previous controller: is it a method of CodeIgniter CI_Controller class or something totally custom defined by the developer that work on this application before me?
A controller can handle more than one URL and the class garanzieValoreFlex is an example of such a class.
The URL http://MYURL/garanzieValoreFlex will call the index method.
The URLs http://MYURL/garanzieValoreFlex/back and http://MYURL/garanzieValoreFlex/reset will call the back() and reset() methods of the class respectively. These two function are custom additions to the extended class CI_Controller.
Codeigniter (CI) URLs follow the pattern example.com/class/function/argument/
The function and argument segments are optional.
When a URL uses only a class name such as example.com/class then CI will look for and call the index() method if it exists. If index() does not exist you will get 404 Page Not Found display.
Your reasoning about $this->load->view('garanziavalore/index_bootstrap',$data); is correct. It is standard to put such files in the views directory. Optionally, subdirectories of views can be used as in /views/garanziavalore/.
CI uses a file structure that associates different classes (libraries) with certain paths. Controllers, Models and View classes are stored in their respective folders. Then the loader class will know exactly where to start looking for any given "type" of class. For instance, the call to $this->load->view('garanziavalore/index_bootstrap',$data); tells the loader class to get the file index_boostrap.php from the /application/views/garanzivalore/ directory. The code $this->load->model('GaranzieValoreFlexModel'); tells the loader to use the file GaranzieValoreFlexModel.php in /application/models/.
Find documentation of the loader class here.
The line of code
$data = $this->session->userdata("datiPreventivo");
is calling the userdata method of the session class (library). Think of session data as an array. If the array was defined this way. (This is only pseudo-code for what is accomplished).
$userdata = array(); //empty array structure
The call $this->session->userdata("datiPreventivo") is in effect returning the value of $userdata["datiPreventivo"].
Your reasoning is wrong. I would really recommend you to read the official codeigniter tutorials so that you may understand how the MVC works:
Below are the links
Codeigniter 2:
http://www.codeigniter.com/userguide2/
Codeigniter 3:
http://www.codeigniter.com/user_guide/
CI controllers handles different urls. If you create a function called index in a controller, it will be loaded automatically when the controller is accessed. For your case, http://MYURL/garanzieValoreFlex should access the function.
To access any other function, you will need to http://MYURL/garanzieValoreFlex/**MyFunction**
(Read more http://www.codeigniter.com/user_guide/general/urls.html?highlight=url#codeigniter-urls) The back function is a user defined function.
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.
a cakePHP newbie here....
I have created a custom helper.
I need to get a session value in this helper and i need to get some data from a table.
How i can make these things possible.
I have tried
var $helper=array('Session');
but then also when i use
$this->Session->read('userid');
it returns error
Undefined property: CustomHelper::$Session
here is the helper in detail
<?php
class CssMenuHelper extends Helper{
var $helpers = array('Html','javascript','Session');
function createMenu(){
$gid=$this->Session->read('Auth.Login.group_id');
}
}
?>
Pay more attention to detail and read the manual. The variable is named var $helpers, plural.
As for accessing tables from Helpers, you shouldn't. It violates MVC separation. Query the data in the Controller, set it to be available in the View and pass it to the Helper function.
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 ...