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.
Related
Not: Its work just one time in loop. Its return this error for other time.
I have a usermodel.php in models. When i use it like
$this->load->model("Usermodel");
$user = $this->Usermodel->quer(1);
it throw "Message: Undefined property: CI_Loader::$Usermodel"
When i use
$this->load->model("Usermodel");
$user = new Usermodel();
it throw "Message: Cannot redeclare class Users"
user class has construct and desturct functions. I call it in Usermodel.php file. And usermodel has construct and destruct functions.
<?php
class User {
public function __construct(){
parent::__construct();
}
private $id;
private $email;
private $name;
private $profilPic;
private $topPic;
private $gender;
private $birthday;
private function setid($id){
$this->id = $id;
}
private function getid(){
return $this->id;
}
private function setemail($email){
$this->email = $email;
}
private function getemail(){
return $this->email;
}
private function setname($name){
$this->name = $name;
}
private function getname(){
return $this->name;
}
private function setprofilPic($profilPic){
$this->profilPic = $profilPic;
}
private function getprofilPic(){
return $this->profilPic;
}
private function settopPic($topPic){
$this->topPic = $topPic;
}
private function gettopPic(){
return $this->topPic;
}
private function setgender($gender){
$this->gender = $gender;
}
private function getgender(){
return $this->gender;
}
private function setbirthday($birthday){
$this->birthday= $birthday;
}
private function getbirhday(){
return $this->birthday;
}
public function __set($name, $value){
$functionname = 'set'.$name;
return $this->$functionname($value);
}
public function __get($name){
$functionname = 'get'.$name;
return $this->$functionname();
}
public function __destruct(){}
}
?>
This is usermodel
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Usermodel extends CI_Model {
public function __construct(){
parent::__construct();
$this->load->view("Users.php");
$this->load->model("Dbmodel");
}
public function quer($id){
$uqcont = array("id" => $id);
$uiqcont = array("userID", $id);
$uq = $this->Dbmodel->control("user", $uqcont);
$uiq = $this->Dbmodel->control("userinfo", $uiqcont, $limit=1, 'userID');
$user = new Users();
if($uq->num_rows()==1){
$uq = $uq->result();
$user->id=$id;
$user->name=$uq[0]->name;
$user->email=$uq[0]->email;
$user->profilPic="girlprofil.png";
$user->topPic="arka.jpg";
}
if($uiq->num_rows()==1){
$uiq=$uiq->result();
if($uiq[0]->profilPic){
$user->profilPic = $uiq[0]->profilPic;
}
if($uiq[0]->topPic){
$user->topPic = $uiq[0]->topPic;
}
}
return $user;
}
public function __destruct(){}
}
?>
This is a part of my view.php
foreach($query->result() as $row){
$cont = array("id" => $row->userID);
$query = $this->Dbmodel->control("user", $cont);
$this->load->model("Usermodel");
$user = new Usermodel();
$user = $user->quer($row->userID);
$date = new datetime($row->date);
$date = $date->format("d.m.Y H:i:s");
//$query = $query->result();
//foreach($query as $qur){
echo '$user->name.'<br>'.$row->comment;
//}
//unset($user);
}
Please look to my error and help me to solve it.
the class User is being declared more than once, probably in the loop you were referring to.
is this line in the loop?
$this->load->model("Usermodel");
if so try moving it out of the loop.
The error is due to loading the model several times in the foreach loop. Load it only once then create instances of the class as many times as you wish
$this->load->model("usermodel");
foreach($query->result() as $row){
$cont = array("id" => $row->userID);
$query = $this->Dbmodel->control("user", $cont);
$user = new Usermodel();
$user = $user->quer($row->userID);
$date = new datetime($row->date);
$date = $date->format("d.m.Y H:i:s");
}
Then consider using small caps in your load->model().
I advise loading the data in the controller then passing the data to the view. Let the controller have most of the logic.For example in the controller
$this->load->model('usermodel');
$data['users'] = $this->usermodel->quer($id)->result();
$this->load->view('users_view', $data);
In the view its as simple as
foreach ($users as $user)
{
//logic e.g. echo $user->name;
}
$this->load->model("X") is doing something like following;
Check models directory if X.php exists and if it exists
it creates the class with the given name in our case "X", [ $this->X = new X(); ]
you can also pass the alternative name to the load->model method like
$this->load->model("X","my_x_model"), in that case the loader module will create
$this->my_x_model = new X();
It was just to give some information about "what happens when you trying to load a model"
You're getting an Undefined property because
$this->load->model("usermodel");
has to be in lowercase.
https://www.codeigniter.com/userguide3/general/models.html#loading-a-model
I change this "class Users" to "class users extends CI_Model" and i move "$this->load->model("usermodel") on over of loop. Then the problem is solved. Thank you for help.
I wrote a class
class User {
private $cars = array(); //store class Car 's object
public function getCars()
{
return $this->cars;
}
public function setCars($cars)
{
$this->cars = $cars;
}
}
class Car{
private $model;
public function getModel()
{
return $this->model;
}
public function setModel($model)
{
$this->model = $model;
}
}
$user = new User();
$cars = $user->getCars();
$cars[0]->getModel();
When I try to access getModel() php report "Call to undefined method stdClass::getModel()" .
Is there the best practice to deal with such case?
Edit:I filled the getter and setter. In fact, It's generated by phpstorm.
Edit:I tried again and it works well with the demo code below. The original code is too complicated to show. Maybe I caused by my misunderstanding of copying by value and by reference of array.
Please ignore this question. sorry.
class User {
private $cars = array(); //store class Car 's object
public function getCars()
{
return $this->cars;
}
public function setCars($cars)
{
$this->cars = $cars;
}
}
class Car{
private $model;
public function getModel()
{
return $this->model;
}
public function setModel($model)
{
$this->model = $model;
}
}
$user = new User();
$car = new Car();
$car->setModel("Ford");
$arr = $user->getCars();
array_push($arr,$car);
$user->setCars($arr);
foreach($user->getCars() as $car) {
var_dump($car->getModel());
}
You haven't shown your [Getter Setter ] code. You need to create one with something like:
public function setCars($val){
$this->cars = $val;
}
public function getCars(){
return $this->cars;
}
The same applies for getModel()
I have just a little progress in practicing. Most of my code works but I am not sure if I do things the right way?
Please, can you tell me if I do mistakes and correct me.
First, I create autoload functions:
function autoload_models($model) {
if (file_exists(MODELS_PATH . $model . '.php')) {
require_once MODELS_PATH . $model . '.php';
return true;
} else {
return false;
}
}
spl_autoload_register('autoload_models');
function autoload_controllers($controller) {
if (file_exists(CONTROLLERS_PATH . $controller . '.php')) {
require_once CONTROLLERS_PATH . $controller . '.php';
return true;
} else {
return false;
}
}
spl_autoload_register('autoload_controllers');
I have a class like this:
class Category {
public $db;
public $rows;
public $id;
public function build_category() {
global $db;
global $rows;
$db = new Database();
$db->query("SELECT * from categories");
$rows = $db->resultset();
}
public function category_items() {
global $db;
global $rows;
global $id;
$db = new Database();
$db->query("SELECT * from posts WHERE category_id = '$id'");
$rows = $db->resultset();
}
}
I extend with another class (still have some issues here. Nothing prints):
class Category_Items extends Category {
public $db;
public $rows;
public $id;
public function display_category_items() {
// Call the parent class function
parent::category_items();
global $rows;
global $id;
// Check if the page parameter is integer
if (ctype_digit($_GET['id'])) {
$id = $_GET['id'];
} else {
print "Illegal category page parameter";
}
foreach ($rows as $row) {
print "test";
print $row['post_title']; // This does not work yet. Nothing prints
}
}
}
Class for building a menu with categories (Everything works here):
class Categories_Menu extends Category {
public $db;
public $rows;
public function build_category_menu() {
parent::build_category();
global $rows;
foreach ($rows as $row) {
require VIEWS_PATH . 'categories/categories_menu.php';
}
}
}
And finally instances:
$category_menu = new Categories_Menu();
$category_menu->build_category_menu();
$category_items = new Category_Items();
$category_items->display_category_items();
Thank you for your time and help!
Where do the global variables come from?
Anyway, you should get rid of them.
I guess your rows var does not get changed, after any interaction. Using globals also will not be relevant in extending classes.
Your public properties and globals mentioned, does no interact each other. Thus, the object members seems to be totally useless.
What I would suggest in simple schems would be
class Model {
protected $_db;
public function __construct(Database $db) {
$this->_db = $db;
}
}
class Category extends Model {
public $_rows;
public $_id;
public function build_category() {
$this->_db->query("SELECT * from categories");
$this->_rows = $this->_db->resultset();
}
public function category_items() {
$this->_db->query("SELECT * from posts WHERE category_id = '{$this->_id}'");
$this->_rows = $this->_db->resultset(); // here you will overwrite $_rows ?
}
class Categories_Menu extends Category {
public $_rows;
public function build_category_menu() {
$this->build_category();
foreach ($this->_rows as $row) {
require VIEWS_PATH . 'categories/categories_menu.php';
}
}
}
class Category_Items extends Category {
public $_rows;
public $_id;
public function display_category_items() {
if (ctype_digit($_GET['id'])) { // just intval it, or use is_int?
$this->_id = $_GET['id'];
} else {
print "Illegal category page parameter";
}
// You assign value to $_id, then call the function that requires it
$this->category_items();
foreach ($this->_rows as $row) {
print "test";
print $row['post_title'];
}
}
}
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);
}
}
So I was trying to make a CRUD for my app. I have setup a controller, like this:
class Clients extends CI_Controller {
public function __construct() {
parent::__construct();
session_start();
$this->c = new Client();
$this->u = new User();
}
function index() {
$data['current_view'] = 'client_view';
$data['header'] = 'Меню клиентов';
$data['clients'] = $this->getClients();
$this->load->view('main_view',$data);
}
function getClients() {
$this->u->where('username',$_SESSION['username'])->get();
$c = $this->c->where('user_id',$this->u->id)->get();
return $c;
}
function delClient() {
$this->c->where('client_id', $this->uri->segment(3))->delete();
$this->c->skip_validation()->save();
$this->index();
}
}
However, when I'm trying to perform a delete on a client, i get a db error:
You must use the "set" method to update an entry.
Filename: C:\OpenServer\domains\localhost\system\database\DB_active_rec.php
Line Number: 1174
What might be the cause of this? I found a similar question here, but I don't think that's the case.
EDIT: Client model:
class Client extends DataMapper {
public $has_one = array('user');
public function __construct($id = NULL) {
parent::__construct($id);
}
}
you have not passed the uri segment to the function delClient() and this is your model right...
function delClient($id) {
//$id is the value which you want to delete
$this->c->where('client_id', $id)->delete();
$this->c->skip_validation()->save();
$this->index();
}