When I load a library in CI controller the class constructor is activated automatically, even if I didn't create an object just yet.
This is weird. can this be fixed via config or something? didn't find anything on the web.
My Controller:
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$this->load->library('users',false);
$user = new Users();
$this->load->model('welcome_model');
$this->load->view('welcome_message');
}
}
My Class:
defined('BASEPATH') OR exit('No direct script access allowed');
class Users {
public function __construct($uname, $fname, $lname) {
print "Hello World!";
}
public function some_method() {
}
}
The code will output "Hello World" twice.
$this->load->library('myLib'); instanciate the library, so you don't need to use the new keyword.
$params_for_the_constructor = array(
'id' => 1,
'firstname' => 'Jemmy',
'lastname' => 'Neutron'
);
$this->load->library('users', $params_for_the_constructor);
$this->users->some_method();
class Users {
private $id;
private $firstname;
private $lastname;
public function __construct(array $params = array()) {
if (count($params) > 0) {
$this->initialize($params);
}
log_message('debug', "Users Class Initialized");
}
public function some_method() {
}
public function initialize(array $params = array()) {
if (count($params) > 0) {
foreach($params as $key => $val) {
if (isset($this->{$key}))
$this->{$key} = $val;
}
}
return $this;
}
}
https://ellislab.com/codeigniter/user-guide/general/creating_libraries.html
in Codeigniter when you call library or call helper or call a controller or a model or anything of these its just equivalent to the new key word.
i mean if you want to make a new object of user you just do the following.
just store the instance of your first user in a varaible.
//creating first instance
$user = $this->load->library('users', $first_user_parameters);
//creating second instance
$user2 = $this->load->library('users', $second_user_parameters);
// $this->load->library('users', $param) === $user = new User($param);
in codeigniter they convert the load to new keyword by the ci_loader
Related
I need function (literally i need the $data) from this model in whole project.
when i call in some controller $data = $this->multi_language_model->multi_lang(); it work fine. But is it possible to call in one place, so I can use in every controller and view.
I autoload the model
$autoload['model'] = array('multi_language_model');
class Multi_language_model extends MY_Model
{
public function __construct() {
parent::__construct();
}
public function multi_lang() {
$data['menu_delivery'] = $this->lang->line('menu_delivery');
$data['menu_quotations'] = $this->lang->line('menu_quotations');
$data['menu_customer_service'] = $this->lang->line('menu_customer_service');
return $data;
}
}
Put this helper function in your any loaded helper:
function get_multi_lang(){
$CI = & get_instance();
$data = array();
$CI->load->helper('language');
$CI->lang->load('menu','english');
$data['menu_delivery'] = $CI->lang->line('menu_delivery');
$data['menu_quotations'] = $CI->lang->line('menu_quotations');
$data['menu_customer_service'] = $CI->lang->line('menu_customer_service');
return $data;
}
Controller:
class Yourclassname extends CI_Controller {
var $menu_delivery = "";
var $menu_quotations = "";
var $menu_customer_service = "";
function __construct() {
parent::__construct();
$data = get_multi_lang();
$this->menu_delivery = $data['menu_delivery'];
$this->menu_quotations = $data['menu_quotations'];
$this->menu_customer_service = $data['menu_customer_service'];
}
public function index(){
echo $this->menu_delivery.'<pre>';
echo $this->menu_quotations.'<pre>';
echo $this->menu_customer_service.'<pre>';die;
}
}
If you dont want to use helper function then copy helper function lines in controller __construct() [replace $data to $this->]so direct use global variables do same in model and for view pass this variable via controller
I don't know how codeigniter works but maybe you could do this method static and use it like:
class Multi_language_model extends MY_Model
{
private static $data = [];
public function get_multi_lang()
{
return [
'menu_delivery' => $this->lang->line('menu_delivery'),
'menu_quotations' => $this->lang->line('menu_quotations'),
'menu_customer_service' => $this->lang->line('menu_customer_service'),
];
}
public static function multi_lang()
{
if (empty(self::$data)) {
self::$data = (new self)->get_multi_lang();
}
return self::$data;
}
}
Then, whenever you need it, you can use $data = Multi_language_model::multi_lang();
However, I don't see anything wrong in injecting it from the container, wherever you need it. Doing so would be much easier to build tests.
BTW you don't need to overwrite the class constructor if there are no custom parameters set to the extending class. You can safely remove:
public function __construct() {
parent::__construct();
}
I want to load a function from another controller. This is my structure:
- modules
--orderpages
---controllers
----WebshopCore.php
----WebshopController.php
My function insertItemInCart in WebshopController.php is called. But when i want to execute a function from another controller it crashes.
class WebshopController extends MX_Controller {
public function __construct() {
parent::__construct();
$this->load->module('orderPages/WebshopCore');
}
function insertItemInCart(){
$partId = $this->input->post('partId');
$quantity = $this->input->post('quantity');
$output = $this->WebshopCore->getPickLocations($partId,$quantity);
}
}
My WebshopCore:
class WebshopCore extends MX_Controller {
public function __construct() {
parent::__construct();
}
public function getPickLocations($partId,$amount){
$result = "test";
return $result;
}
}
What goes wrong? I don't get it
The solution:
$output = modules::load('orderPages/WebshopCore/')->getPickLocations($partId,$quantity);
You should write a library in that case.
In application/libraries create Cart.php (or whatever you want)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Cart
{
protected $ci;
public function __construct()
{
$this->ci =& get_instance();
}
public function getPickLocations($partId, $qty)
{
//Your stuff
}
}
And then in your controllers :
$this->load->library("cart");
$data = $this->cart->getPickLocations($this->input->post('partId'), $this->input->post('quantity'));
I need to use a session information in various functions of my controller, but I can't initialize it in the constructor, because I get an error. Message: Undefined property: Soporte::$session
class Soporte extends MY_Controller {
function __construct(){
parent::__construct( $module, $functionality );
}
public function actualizarSolicitud( $id_solicitud ){
$session_data = $this->session->userdata('session_user');
$user = $session_data['usuario'];
...
}
public function adminHistorico(){
$session_data = $this->session->userdata('session_user');
$user = $session_data['usuario'];
$config = array();
...
}
...
}
There's a way to initialize a global variable $user?
Try like below, model is quite complicated so I'm not providing it's code, but you should get the point. Any questions let me know.
/**
* This class is used for performing all read/write session operations
* Native php session is utilized (MY_Session library)
*/
class SessionManager extends BaseLibrary {
private $oUser;
public function __construct() {
parent::__construct();
$this->CI->load->model('User');
}
public function setUser(User $oUser) {
$this->CI->session->set_userdata('userId', $oUser->getId());
}
public function getUser() {
if ($this->oUser === null) {
$this->oUser = new User();
if ($this->CI->session->userdata('userId')) {
$this->oUser->setId($this->CI->session->userdata('userId'));
}
}
return $this->oUser;
}
public function logout() {
$this->CI->session->set_userdata('userId', NULL);
}
}
I am trying to create a new model object from my mvc controller but the page doesn't generate. Is there any reason why I can't do this? Surely I should be able to create an object inside an existing one?
Sorry to be so simplistic, and I know I sound like an idiot, but I'm not sure how to explain what I am doing wrong.
class controller_landing extends controller_base
{
public function __construct($get,$post)
{
parent::__construct($get,$post);
$this->model = new model_landing; <-----problem line here
}
}
abstract class controller_base
{
//store headers
protected $get;
protected $post;
//store layers
protected $view;
protected $model;
protected function __construct($get,$post)
{
//store the header arrays
$this->get = $get;
$this->post = $post;
//preset the view layer as an array
$this->view = array();
}
public function __destruct()
{
//extract variables from the view layer
extract($this->view);
//render the view to the user
require_once('view/'.$this->get['controller'].'_view.php');
}
}
class model_landing extends class_mysqli
{
public function __construct
{
echo "landing model";
}
}
class class_mysqli
{
public function __construct
{
echo "mysqli";
}
}
I donĀ“t know, but I think you are missing brackets.
There
public function __construct
{
echo "landing model";
}
should be
public function __construct()
{
echo "landing model";
}
OK...first I read this article..
http://net.tutsplus.com/tutorials/php/6-codeigniter-hacks-for-the-masters/
In the first hack, it says if I include these in my config.php file:
function __autoload($class) {
if (file_exists(APPPATH."models/".strtolower($class).EXT)) {
include_once(APPPATH."models/".strtolower($class).EXT);
}
}
I don't need to extend my model class to CI_Model.
Then the I tried to use $this->db->select('email')->from('users')->where('email', $email); in my model class..CodeIgniter tells me "db" property is not found. Has anyone tried this hack before and know how to get it to work?
class User {
public $id;
public $email;
public $displayName;
public $password;
public static function search_by_email($email) {
$user = new User;
$user->db->select('email')->from('users')->where('email', $email);
$query = $user->db->get();
if ($query->num_rows()==0) {
return false;
}else {
foreach ($query->result() as $key => $val) {
$user->email = $val['email'];
$user->displayName = $val['displayName'];
return $user;
}
}
return null;
}
When I call the static function in my controller I use:
$user = User::search_by_email("xxx#gmail.com");
If I don't extend User, it will show a CI warning: Message: Undefined property: User::$db. If I use User extends CI_Model {}, the server will crash.
Does anyone have an idea about this situation?
Edited:
Then I dumped the silly Nettus' tutorial code, thanks to you guys...but my model is still not working:
class User extends CI_Model {
public $id;
public $email;
public $displayName;
public $password;
public function search_by_email($email) {
$user = new User();
$this->db->select('email')->from('users')->where('email', $email);
$query = $this->db->get();
if ($query->num_rows()==0) {
return false;
}else {
foreach ($query->result() as $key => $val) {
$user->email = $val['email'];
$user->displayName = $val['displayName'];
return $user;
}
}
return null;
}
In my controller I use:
$this->load->model('User');
$user = $this->User->search_by_email("leo.niecn#gmail.com");
My server still crashed.....am I forbidden to write class variables like public $id in my model?
This part of code doesn't make any sense:
function __autoload($class) {
if (file_exists(APPPATH . "models/" . strtolower($class).EXT)) {
include_once(APPPATH . "models/" . strtolower($class).EXT);
}
}
as long as you can load your model from autoload.php under config folder or just do the following when you need the model:
$this->load->model('model_name');
then just call your function.