declaring class level variables in codeigniter - codeigniter

I am new to CI and what I want to do is to have a class level variable (which e.g is an array). But it seems like CI, despite all high bragging, doesn't support this feature. Nothing has been mentioned in the user guide about it. There is a heading called private functions and variables but the text has been seemingly kept silent regarding variables.
I want to have something like :
class OrderStats extends CI_Controller {
protected $arr_CoreCountry = ('0'=>'uk', '1'=>'us');
public function __construct()
{
parent::__construct();
// Your own constructor code
}
public function index()
{
$this->load->model('orders', '', TRUE);
//$data['result'] = $this->Testmodel->get_entries();
$data['result'] = $this->Testmodel->get_reports();
$this->load->view('test', $data);
}
public function getOrderStats()
{
$this->load->model('Orderstatsmodel', '', TRUE);
//$data['result'] = $this->Testmodel->get_entries();
foreach ($arr_CoreCountry as $key => $value)
{
$data['result'] = $this->Orderstatsmodel->get_orderStats($key);
}
// $data['result'] = $this->Orderstatsmodel->get_orderStats(0);
$this->load->view('orderstats', $data);
}
Remember, when I declare $arr_CoreCountry variable at the place as it is in this post, I constantly see a syntax error message.
When I place it some where inside any function then of course, it gets out of scope and I keep getting an error messag that $arr_CoreCountry is an undefined variable.
So the question is where do I define it?
Expect a quick response as half of my day has been wasted just because of this s*** from codeigniter.

This should work:
class OrderStats extends CI_Controller {
protected $arr_CoreCountry = array('0'=>'uk', '1'=>'us');
public function getOrderStats()
{
$this->load->model('Orderstatsmodel', '', TRUE);
//$data['result'] = $this->Testmodel->get_entries();
foreach ($this->arr_CoreCountry as $key => $value)
// etc
}
you are omitting the $this-> in your original code.
Edit
Here was my test code ~
class Testing extends CI_Controller {
protected $foo = array('test'=>'foo', 'bar'=>'baz');
function index() {
foreach($this->foo as $k => $v) {
echo $k . ' = ' . $v . '<br />';
}
}
}
// outputs:
test = foo
bar = baz
perhaps you can post your syntax errors as they appear to be missing from your original post.

You have a syntax array declaration error. Please try to declare array like this:
protected $arr_CoreCountry = array('0'=>'uk', '1'=>'us');
Please check out this site for array manual: http://php.net/manual/en/language.types.array.php

I solved the problem myself.
There are two things which I changed
protected $arr_CoreCountry = ('0'=>'uk', '1'=>'us');
was changed to
var $arr_CoreCountry = array(0=>'se', 1=>'fi',2=>'de');
and
foreach ($arr_CoreCountry as $key => $value)
was changed to
foreach ($this->arr_CoreCountry as $key => $value)
I was missing $this but when I put it there, it was still not working. When I changed protected to var, it worked.
Thanks everyone for your input...

Related

how can i get language value randomly in laravel controller?

class DynamicDependent extends Controller
{
function fetch(Request $request)
{
$value = "home";
$value2 = Lang::get('home.'.$value.'');
}
}
output :'home.home'.
But i need value from language file.
please guide me to get this.
It seems like you are trying to get a translation. For that you can use the trans helper method like this:
//In your resources/lang/{some_lang_code}/home.php
return [
'home' => 'My translation',
];
//In your controller
$value = "home";
$value2 = trans('home.'.$value); //My translation

how to pass two arrays from model file to controller file

I want to return two arrays in a single function in the model and post the result in view but it gives an error.
And also I want to output a certain element of an array.
public function index(){
$this->load->model("model");
$array['thisarray'] = $this->model->Hello();
$arrayy['yep'] = $this->model->Hello();
$this->load->view("viewfile",$array);
$this->load->view("viewfile",$arrayy);
}
below is my model.php file.
public function Hello()
{
return ['title' => 'My Title','heading' => 'My Heading'];
return ['a'=> "helo",'b' =>"yello", 'c' =>"mello"];
}
below is my view file
<?php
echo "<pre>";
print_r($thisarray);
print_r($yep)
echo "</pre>"
?>
it gives an error saying yep is undefined variable.
this is impossible
a possible solution would be
your model
public function Hello()
{
return
[
'yep' => ['title' => 'My Title','heading' => 'My Heading'],
'thisarray' => ['a'=> "helo",'b' =>"yello", 'c' =>"mello"]
];
}
your controller
public function index()
{
$this->load->model("model");
$this->load->view("viewfile",$this->model->Hello());
}
and your view stays the same
you need to just change just your controller like this and you are all set.
public function index()
{
$this->load->model("model");
$array['thisarray'] = $this->model->Hello();
$array['yep'] = $this->model->Hello();
$this->load->view("viewfile", $array);
}
After modifying your controller like given above, you will be able to access you array as you are accessing it in your view.

Loading view inside a Library, issues with cached vars

I am trying to implement a widgets library using load->view. I know I can use include to call directly the file and avoid the vars cache issues but just wondering why it does not work.
Here is how I have structured my code:
My Controller:
class Page extends MY_Controller {
public $data = array();
public function __construct() {
parent::__construct();
...
$this->load->library('widgetmanager');
}
public function index($slug = '') {
echo $this->widgetmanager->show(2);
echo $this->widgetmanager->show(1);
}
}
My Library
class WidgetManager
{
private $CI;
public function __construct()
{
$this->CI = & get_instance();
}
public function show($widget_id) {
$data = array();
$widget_id = (int)$widget_id;
$this->CI->db->select('*');
$this->CI->db->from('widget');
$this->CI->db->where('id', $widget_id);
$query = $this->CI->db->get();
$item = $query->row_array();
$data['widget_title'] = $item['title'];
$data['widget_content'] = $item['content'];
$widget = $this->CI->load->view('widget/'.$item['source'], $data, TRUE);
$data['widget_title'] = '';
$data['widget_content'] = '';
$this->CI->load->view('widget/'.$item['source'], $data);
return $widget;
}
}
widget 1: Calls widget/content
widget 2: Calls widget/banner
What is happening is, the vars set on the first widget call (they are same name as second widget call), get cached, meaning values from the first call are passed to same call. It is weird because are different views.
I have tried:
Using clear_vars(): $this->CI->load->clear_vars(), before and after doing load->view on the library.
Calling load->view with empty array, null, etc
Tried to add a prefix with the widget slug to the vars (that works, but I have to send in some way the prefix to the view, so it is not possible due cache issue)
Any ideas?
Here is what should work.
(I took the liberty of simplifying your database call making it require much less processing.)
public function show($widget_id)
{
$data = array();
$widget_id = (int) $widget_id;
$item = $this->CI->db
->get_where('widget', array('id' => $widget_id))
->row_array();
$data['widget_title'] = $item['title'];
$data['widget_content'] = $item['content'];
$widget = $this->CI->load->view('widget/'.$item['source'], $data, TRUE);
//clear the cached variables so the next call to 'show()' is clean
$this->CI->load->clear_vars();
return $widget;
}
On further consideration The call $this->CI->load->clear_vars(); is probably pointless because each time WidgetManager::show() is called the $data var is recreated with exactly the same keys. When the $data var is passed to load->view the new values of $data['widget_title'] and $data['widget_content'] will replace the values in the cached vars using those keys.

load multiple models in array - codeigniter framework

<?php
class Home extends CI_Controller
{
public function __construct()
{
// load libraries //
$this->load->library('session');
$this->load->library('database');
$this->load->library('captcha');
// alternative
$this->load->library(array('session', 'database', 'captcha'));
// load models //
$this->load->model('menu_model', 'mmodel');
$this->load->model('user_model', 'umodel');
$this->load->model('admin_model', 'amodel');
// alternative
$this->load->model(array(?));
}
}
?>
How can i load all models in array? is it possible?
For models, you can do this:
$models = array(
'menu_model' => 'mmodel',
'user_model' => 'umodel',
'admin_model' => 'amodel',
);
foreach ($models as $file => $object_name)
{
$this->load->model($file, $object_name);
}
But as mentioned, you can create file application/core/MY_Loader.php and write your own method for loading models. I think this might work (not tested):
class MY_Loader extends CI_Loader {
function model($model, $name = '', $db_conn = FALSE)
{
if (is_array($model))
{
foreach ($model as $file => $object_name)
{
// Linear array was passed, be backwards compatible.
// CI already allows loading models as arrays, but does
// not accept the model name param, just the file name
if ( ! is_string($file))
{
$file = $object_name;
$object_name = NULL;
}
parent::model($file, $object_name);
}
return;
}
// Call the default method otherwise
parent::model($model, $name, $db_conn);
}
}
Usage with our variable from above:
$this->load->model($models);
You could also allow a separate DB connection to be passed in an array, but then you'd need to have a multidimensional array, and not the simple one we used. It's not too often you'll need to do that anyways.
I don't have any idea about the CodeIgniter 2.x but in CodeIgniter 3.x, this will also works :
$models = array(
'menu_model' => 'mmodel',
'user_model' => 'umodel',
'admin_model' => 'amodel',
);
$this->load->model($models);
Not natively, but you can easily extend Loader->model() to support that logic.
This work fine for me:
$this->load->model(array('menu_model'=>'menu','user_model'=>'user','admin_model'=>'admin'));

Codeigniter MVC Sample Code

Hi
I am following the getting started guide for Codeigniterr given at http://www.ibm.com/developerworks/web/library/wa-codeigniter/
I have followed the instruction to create the front view and added controller to handle form submission. Ideally, when i submit the form, it should load the model class and execute the function to put details on the database, but instead it is just printing out the code of the model in the browser.
**Code of view (Welcome.php)**
----------------
<?php
class Welcome extends Controller {
function Welcome()
{
parent::Controller();
}
function index()
{
$this->load->helper('form');
$data['title'] = "Welcome to our Site";
$data['headline'] = "Welcome!";
$data['include'] = 'home';
$this->load->vars($data);
$this->load->view('template');
}
function contactus(){
$this->load->helper('url');
$this->load->model('mcontacts','',TRUE);
$this->mcontacts->addContact();
redirect('welcome/thankyou','refresh');
}
function thankyou(){
$data['title'] = "Thank You!";
$data['headline'] = "Thanks!";
$data['include'] = 'thanks';
$this->load->vars($data);
$this->load->view('template');
}
}
/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */
**Code of Model**
--------------
class mcontacts extends Model{
function mcontacts(){
parent::Model();
}
}
function addContact(){
$now = date("Y-m-d H:i:s");
$data = array(
'name' => $this->input->xss_clean($this->input->post('name')),
'email' => $this->input->xss_clean($this->input->post('email')),
'notes' => $this->input->xss_clean($this->input->post('notes')),
'ipaddress' => $this->input->ip_address(),
'stamp' => $now
);
$this->db->insert('contacts', $data);
}
**OUTPUT after clicking submit**
-----------------------------
class mcontacts extends Model{ function mcontacts(){ parent::Model(); } } function addContact(){ $now = date("Y-m-d H:i:s"); $data = array( 'name' => $this->input->xss_clean($this->input->post('name')), 'email' => $this->input->xss_clean($this->input->post('email')), 'notes' => $this->input->xss_clean($this->input->post('notes')), 'ipaddress' => $this->input->ip_address(), 'stamp' => $now ); $this->db->insert('contacts', $data); }
I have tried doing these things
1. Making all PHP codes executable
2. Change ownership of files to www-data
3. make permission 777 for whole of www
But, the code of model seems to be just printed ... PLEASE HELP
Just a few minor points that might help you:
In your controller, point the index method at the method you would like to call on that page. For example:
function index()
{
$this->welcome();
}
That will help keep things clean and clear, especially if anyone else comes in to work on the code with you later. I chose welcome because that's the name of your controller class and that will keep things simple.
In your model, this:
class mcontacts extends Model{
Should be:
class Mcontacts extends Model{
Capitalize those class names! That could be giving you the trouble you describe.
See here for more info on this: http://codeigniter.com/user_guide/general/models.html
Don't use camel case in your class or method names. This isn't something that will cause your code to fail, but it's generally accepted practice. See Codeigniter's PHP Style guide for more information on this: http://codeigniter.com/user_guide/general/styleguide.html
It's difficult to see with the formatting as it is, but do have an extra curly brace after the constructor method (mcontacts()) in the model? This would cause problems! Also although the code looks generally ok, there are probably better ways to use the framework especially if you do anything more complicated than what you've shown. For example, autoloading, form validation etc. Can I suggest you have a read of the userguide? It's very thorough and clear and should help you alot. http://codeigniter.com/user_guide/index.html

Resources