Yii create a new attribute in the model doesn't work - php

I need to create a new attribute in the model and something weird is happening:
this code, works fine:
class Person extends CActiveRecord {
public $test = "xxx";
public function getRandomToken() {
$temp = $this->test;
return $temp;
}
this code, does not:
class Person extends CActiveRecord {
public $test = md5(uniqid(rand(), true));
public function getRandomToken() {
$temp = $this->test;
return $temp;
}
why?
I get a blank page with the second code, with no errors.
I will need to use the random token from create view-page and I'm doing it in this way:
echo $model->getRandomToken();
Thank you for your support!

You cannot assign a function result as value. It must be a constant. Assign the function value in the constructor
public $test = '';
function __construct() {
$this->test = md5(uniqid(rand(), true));
}

If you do not want to overwrite the contructor you can use this:
class Person extends CActiveRecord {
public $test = null;
public function getRandomToken() {
if ($this->test == null){
$this->test = md5(uniqid(rand(), true));
}
$temp = $this->test;
return $temp;
}

Related

Codeigniter cannot redeclare class

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.

PHP class array object method access issue

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()

Array reference in a class error in php

I have this class which populates and prints an array
<?php
class testArray
{
private $myArr;
public function __construct() {
$myArr = array();
}
public static function PopulateArr() {
$testA = new testArray();
$testA->populateProtectedArr();
return $testA;
}
protected function populateProtectedArr()
{
$this->myArr[0] = 'red';
$this->myArr[1] = 'green';
$this->myArr[2] = 'yellow';
print_r ($this->myArr);
}
public function printArr() {
echo "<br> 2nd Array";
print_r ($this->myArr);
}
}
?>
I instantiate this class from another file and try to print the array in different function.
<?php
require_once "testClass.php";
$u = new testArray();
$u->PopulateArr();
$u->printArr();
?>
I am not able to print the array in the printArr() function. I want to get reference to the array that I had set the values in .
You just missed one thing, you have to assign result of $u->PopulateArr(); to $u again, otherwise you will not get the object you created from that method call, so:
$u = new testArray();
$u = $u->PopulateArr(); // this will work
$u->printArr();
This also can be done like this:
$u = testArray::PopulateArr();
$u->printArr();
It seems that your $u object never populates the private array.
Instead you create a new object $testA and populate its array.
This might help you understanding the way
class testArray
{
private $myArr;
public function __construct() {
$this->myArr = array();
}
public static function PopulateArr() {
$testA = new testArray();
$testA->populateProtectedArr();
return $testA;
}
protected function populateProtectedArr()
{
$this->myArr[0] = 'red';
$this->myArr[1] = 'green';
$this->myArr[2] = 'yellow';
return $this->myArr;
}
public function printArr() {
echo "<br> 2nd Array";
return $this->PopulateArr();
}
}
another.php
require_once "testClass.php";
$u = new testArray();
print_r($u->PopulateArr());
print_r($u->printArr());
Here we are accessing the values of protected function PopulateArr instead of printing within function I just replaced it with return and print it over another file and within printArr function just call the PopulateArr function and that's it

How to access a variable with random value inside a class?

class Session{
protected $git = md5(rand(1,6));
public function __construct($config = array())
{
//// some code
$ses_id = $this->git;
}
public function _start_session()
{
//code again..
}
}
Here I can't assign a random value like this to variable called git. How can I do this if it is possible?
That random value need to be first time generated value only till the time it converts to Null.
Perform random inside your constructor,
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
$this->git = md5(rand(1,6));
$ses_id = $this->git;
}
public function _start_session()
{
//code again..
}
}
Try setting the value of your variable in your constructor.
constructor will run every time you create an instance of your class.
try this code:
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
$this->git = md5(rand(1,6));
}
public function _start_session()
{
//code again..
}
}
:)
Declare a variable inside a class,initialize the variables in class inside a constructor, which sets the variables once the object for that class is declared anywhere in the code.
I updated this answer if you want to do not change your session variable on each constructor call then use the below procedure.
class Session{
protected $git;
public function __construct($config = array())
{
$this->git = md5(rand(1,6));
if(!isset($_SESSION['ses_id']))
{
$_SESSION['ses_id'] = $this->git;
}
}
public function _start_session()
{
//code again..
}
}
I hope this helps you.
Try this using a global variable to track the random number:
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
if (!isset($GLOBALS['random_val'])) {
$GLOBALS['random_val'] = md5(rand(1,6));
}
$this->git = $GLOBALS['random_val'];
$ses_id = $this->git;
var_dump("Session ID: ".$ses_id);
}
public function _start_session()
{
//code again..
}
}
$ses1 = new Session(); // Outputs string(44) "Session ID: 1679091c5a880faf6fb5e6087eb1b2dc"
$ses2 = new Session(); // Outputs string(44) "Session ID: 1679091c5a880faf6fb5e6087eb1b2dc"

What is the difference between setter methods and construct methods?

If I have a setter and getter methods below :
<?php
class Name{
protected $first ;
public function setNameType($value) {
$this->first = $value;
}
public function getNameType() {
return $this->first;
}
}
$name = new Name;
$name->setNameType("My Name");
echo $name->getNameType();
?>
and a construct method like this
<?php
class Name{
protected $first ;
public function __construct($value) {
$this->first = $value;
}
public function getNameType() {
return $this->first;
}
}
$name = new Name("My Name");
echo $name->getNameType();
?>
Can I use the two interchangeably at all times or is there situations where one will be most prefered over the other ?
There is also some great explaination about your question: http://www.potstuck.com/2009/01/08/php-dependency-injection/
Try this website. It explains all with examples.
http://ralphschindler.com/2012/03/09/php-constructor-best-practices-and-the-prototype-pattern
Generally you would use constructors to set values if your class cannot exist or doesn't make sense without the value. If the value is allowed to be changed, than add a setter. If it should never be changed after construction, then don't add a setter.
An example code:
class Book {
public function __construct() {
$registry = RegistrySingleton::getInstance();
$this->_database = $registry->database;
// or
global $databaseConnection;
$this->_database = $database;
}
}
class Book {
private $_databaseConnection;
public function __construct() { }
public function setDatabaseConnection($databaseConnection) {
$this->_databaseConnection = $databaseConnection;
}
}
$book = new Book();
$book->setDatabase($databaseConnection);
$book = new Book($databaseConnection, $configFile);
$book = new Book();
$book->setDatabase($databaseConnection);
$book->setConfigFile($configFile);
class Container {
public static $_database;
public static function makeBook() {
$book = new Book();
$book->setDatabase(self::$_database);
// more injection...
return $book;
}
}
And then:
$book = Container::makeBook();

Categories