I am really new to Codeigniter, and just learning from scratch. In the CI docs it says:
$params = array('type' => 'large', 'color' => 'red');
$this->load->library('Someclass', $params);
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Someclass {
public function __construct($params)
{
// Do something with $params
}
}
Can you give me simple example how to pass data from controller to external library using array as parameters? I'd like to see a simple example.
All Codeigniter "library" constructors expect a single argument: an array of parameters, which are usually passed while loading the class with CI's loader, as in your example:
$params = array('type' => 'large', 'color' => 'red');
$this->load->library('Someclass', $params);
I'm guessing you're confused about the "Do something with $params" part. It's not necessary to pass in any params, but if you do you might use them like this:
class Someclass {
public $color = 'blue'; //default color
public $size = 'small'; //default size
public function __construct($params)
{
foreach ($params as $property => $value)
{
$this->$property = $value;
}
// Size is now "large", color is "red"
}
}
You can always re-initialize later like so, if you need to:
$this->load->library('Someclass');
$this->Someclass->__construct($params);
Another thing to note is that if you have a config file that matches the name of your class, that configuration will be loaded automatically. So for example, if you have the file application/config/someclass.php:
$config['size'] = 'medium';
$config['color'] = 'green';
// etc.
This config will be automatically passed to the class constructor of "someclass" when it is loaded.
In libraries directory create one file Someclass_lib.php
Here is your Library code
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Someclass_lib
{
public $type = '';
public $color = '';
function Someclass_lib($params)
{
$this->CI =& get_instance();
$this->type = $params['type'];
$this->color = $params['color'];
}
}
Use this code when you want to load library
$params = array('type' => 'large', 'color' => 'red');
$this->load->library('Someclass_lib', $params);
Related
I am getting error -
localhost redirected you too many times.
in hooks
This is my code in hooks.I am unable to resolve this issue please help me
and please explain how to use hooks in ci and i am using post_controller_constructor
<?php
class Example {
private $CI;
function __construct()
{
$this->CI =& get_instance();
if(!isset($this->CI->session)){ //Check if session lib is loaded or not
$this->CI->load->library('session'); //If not loaded, then load it here
}
//echo "class".$this->CI->router->class; die;
if ( $this->CI->router->class == 'student' )
{
return;
}
}
public function check_login()
{
echo $session_userdata = $this->CI->session->userdata('email');
echo "session data".$session_userdata;
// die;
if(empty($session_userdata)) {
redirect("student/index");
}
else {
echo "here";
}
}
}
?>
i'm guessing your hook array looks like
$hook['post_controller_constructor'] = array(
array(
'class' => 'Example',
'function' => 'check_login',
'filename' => 'Example.php',
'filepath' => 'hooks'
),
);
It doesn't really matter whether you return anything in your constructor or not - a constructor serves only one purpose - to instantiate their respective class.
So basically you have to do something like
class Example {
private $CI;
function __construct()
{
$this->CI =& get_instance();
if(!isset($this->CI->session)){ //Check if session lib is loaded or not
$this->CI->load->library('session'); //If not loaded, then load it here
}
}
public function check_login()
{
echo $session_userdata = $this->CI->session->userdata('email');
echo "session data".$session_userdata;
// die;
if(empty($session_userdata) && $this->CI->router->class !== 'student') {
redirect("student/index");
}
else {
echo "here";
}
}
}
First of all, if you are using hooks in the CodeIgniter for the first time then follow some steps.
Step1: Enabling Hooks
The hooks feature can be globally enabled in the application/config/config.php file
Open config.php file does following replaces
$config['enable_hooks'] = FALSE;
To
$config['enable_hooks'] = TRUE;
Step2: Defining a Hook
Hooks are defined in the application/config/hooks.php file.
$hook['post_controller'] = array(
'class' => 'firstHookFile',
'function' => 'checkHook',
'filename' => 'firstHookFile.php',
'filepath' => 'hooks'
);
Step3: Create hook file
Create file in the application/hooks.
<?php
class firstHookFile
{
public function checkHook()
{
// load the instance
$this->CI =& get_instance();
$this->CI->load->helper('uri');
echo base_url();
return;
}
}
?>
This hook is only for example purpose, this hook will return the base URL of your project.
I hope you have understood how to use hooks in Codeigniter.
I have some problem with routing and parameters.
I have routing in routes.php like this :
$route['register/(:any)'] = 'member/register/$1';
And in my controller I have like this :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Register extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Page_model');
$this->load->model('member_model');
$this->load->model('login_model');
$this->load->library('session');
$this->load->helper('url');
$this->load->helper('html');
$this->load->helper('form');
}
public function index()
{
$slug = $this->uri->segment(1);
$type = $this->uri->segment(2);
var_dump($type);
exit();
if ($slug != NULL)
{
$data['page'] = $this->Page_model->get_page($slug);
if (empty($data['page']))
{
// show_404();
$data['page'] = new stdClass();
$data['page']->page_template = 'forofor';
$data['page']->title = 'Page Not Found';
$data['page']->meta_description = 'Page Not Found';
$data['page']->meta_keywords = 'Page Not Found';
}
else
{
$data['slider'] = $this->Page_model->get_slider($data['page']->page_id);
}
}
else
{
$data['page'] = $this->Page_model->get_page('home');
$data['slider'] = $this->Page_model->get_slider($data['page']->page_id);
}
$data['head_title'] = $data['page']->title;
// load all settings and data
$data['settings'] = $this->Page_model->get_settings();
$data['gallery'] = $this->Page_model->get_gallery();
$data['meta'] =
array(
array(
'name' => 'description',
'content' => $data['page']->meta_description
),
array(
'name' => 'keywords',
'content' => $data['page']->meta_keywords
)
);
// $data['meta'] = $this->meta;
$data['menu'] = $this->Page_model->get_menu('frontend','header');
$data['settings'] = $this->Page_model->get_settings();
$data['notice'] = $this->session->flashdata('notice');
// $this->load->view('frontend/template/index_full', $data);
$this->load->view('frontend/template/head', $data);
$this->load->view('frontend/template/pre_header');
$this->load->view('frontend/template/header');
$this->load->view('frontend/template/modal');
//$this->load->view('frontend/template/modal_registration');
/*if ($page[0]->page_template != 'forofor' && $data['page']->slider != 0)
{
$this->load->view('frontend/template/slider');
}*/
if ($slug != 'home' && $slug != NULL)
{
//$this->load->view('member/'.$data['page']->page_template);
$this->load->view('member/register');
}
else
{
$this->load->view('frontend/template/slider');
$this->load->view('frontend/page_template/homepage');
}
$this->load->view('frontend/template/pre_footer');
$this->load->view('frontend/template/footer');
$this->load->view('frontend/template/js');
$this->load->view('frontend/template/closing_body_html');
}
}
But if I input the routes in my browser it gives me 404 Page not found
This is my routes :
127.0.0.1/project/register/buyer
And 127.0.0.1/project/ is my Base URL
Anyone knows why it could be happen ?
Thank you.
Your routing is wrong. According to your post you are setting Member controller then register method.
Try below code
$route['register/(:any)'] = 'register/index/$1';
$route['register/(:any)/(:any)'] = 'register/index/$1/$2'; // Optional
The second option is only optional:
This is how routes work in Codeigniter
Typically there is a one-to-one relationship between a URL string and
its corresponding controller class/method. The segments in a URI
normally follow this pattern:
example.com/class/function/id/ In some instances, however, you may
want to remap this relationship so that a different class/method can
be called instead of the one corresponding to the URL.
For example, let’s say you want your URLs to have this prototype:
example.com/product/1/ example.com/product/2/ example.com/product/3/
example.com/product/4/ Normally the second segment of the URL is
reserved for the method name, but in the example above it instead has
a product ID. To overcome this, CodeIgniter allows you to remap the
URI handler.
Reference : https://www.codeigniter.com/userguide3/general/routing.html
So,the routes follow this syntax
$route['route_url'] = 'controller/method/$paramater';
So,your route will be
Let me know your queries
$route['register/(:any)'] = 'register/index/$1';
I have using a lot config form_validation file. It's working good!
But now I'm trying to get it work with controller in subfolder
/controllers/panel/users.php
My form_validation config file looks like
$config = array(
'panel/users/edit/' => array(
array('field' => 'login', 'label' => 'Логин', 'rules' => "trim|required|valid_email")
)
And my Users controller is
public function edit($user_id = FALSE)
{
if ($this->input->post('save'))
{
$this->load->library('form_validation');
if ($this->form_validation->run())
{
// Do some
}
}
}
But $this->form_validation->run() is always return FALSE
It isn't designed to work this way, there was a relevant change to ruri_string() #122 which would have fixed this but it had other repercussions and needs to be rethought.
You can call your validation rule group explicitly (drop the trailing slash from your rule group name)
if ($this->form_validation->run('panel/users/edit'))
or, if appropriate in your situation, workaround this by prepending uri->segment(1) to the auto-detected rule group.
application/libraries/MY_Form_validation.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
function run($group = '')
{
// Prepend URI to match subfolder controller validation rules
$uri = ($group == '') ? $this->CI->uri->segment(1) . $this->CI->uri->ruri_string() : $group;
return parent::run($uri);
}
}
I would like to add some strings/values to the end of the generated pagination link.
For example, I get this
http://localhost/products/lists/5
I would like to have
http://localhost/products/lists/5/value/anothervalue
So, I need to send those values somehow... :)
Thank u all.
The pagination class has an undocumented configuration option called suffix that you can use. Here's how I use it in one of my apps:
// get the current url segments and remove the ones before the suffix
// http://localhost/products/lists/5/value/anothervalue
$args = $this->uri->segment_array();
unset($args[1], $args[2], $args[3]);
$args = implode('/', $args);
// $args is now 'value/anothervalue'
$base_url = 'http://localhost/products/lists';
$this->pagination->initialize(array(
'base_url' => $base_url,
'suffix' => '/'.$args,
'first_url' => $base_url.'/1/'.$args,
'uri_segment' => 3
));
The application/config/routes.php
$route['products/lists/(:num)/value/(:any)'] = "products/lists/$1/$2";
The controller code application/controllers/products.php
class Products extends CI_Controller {
public function index() {
$this->load->view('welcome_message');
}
public function lists($page = 1, $value = null) {
$this->load->view('product_lists', array('page' => $page, 'value' => $value));
}
}
In this way if your url is like http://localhost/products/lists/5/value/anothervalue
in function lists will be $page = 5 and $value = 'anothervalue' and they will be available in template product_lists ($page, $value)
<?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'));