Simple ORM Structure Codeigniter - php

This is my code:
<?php
class VortexORM {
private static $orm = null;
public function __get($name) {
return $this->$name;
}
public function __set($name, $value) {
$this->$name = $value;
}
public static function getInstance() {
if (VortexORM::$orm == null)
VortexORM::$orm = new VortexORM();
return VortexORM::$orm;
}
public static function set($name, $value) {
$orm = VortexORM::getInstance();
//echo "Setting [ <b>{$name}</b> :: <i>{$value}</i>]";
$orm->$name = $value;
}
public static function get($name) {
$orm = VortexORM::getInstance();
// echo "Getting [ <b>{$name}</b> :: <i>{$orm->$name}</i>]";
return $orm->$name;
}
}
To get data I use:
var_dump(VortexORM::get('admin_links'));
var_dump(VortexORM::get('admin'));
To set data I use:
VortexORM::set('admin_links',array(....));
However, I get the following warnings:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: VortexORM::$admin_links
Filename: Vortex/VortexORM.php
Line Number: 8
NULL
A PHP Error was encountered
Severity: Notice
Message: Undefined property: VortexORM::$admin
Filename: Vortex/VortexORM.php
Line Number: 8
Why am I getting these warnings?
I want to be able to access it like this in CodeIgniter as a static function:
$this->vortexorm->admin_links = array(....);

OK, I just tested this code:
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class VortexORM {
private static $orm = null;
public function __get($name) {
return $this->$name;
}
public function __set($name, $value) {
$this->$name = $value;
}
public static function getInstance() {
if (VortexORM::$orm == null)
VortexORM::$orm = new VortexORM();
return VortexORM::$orm;
}
public static function set($name, $value) {
$orm = VortexORM::getInstance();
//echo "Setting [ <b>{$name}</b> :: <i>{$value}</i>]";
$orm->$name = $value;
}
public static function get($name) {
$orm = VortexORM::getInstance();
// echo "Getting [ <b>{$name}</b> :: <i>{$orm->$name}</i>]";
return $orm->$name;
}
}
VortexORM::set('admin_links',"test");
var_dump(VortexORM::get('admin_links'));
It just worked fine for me. giving the following output:
string(4) "test"
So, I guess, you were might just trying to retrieve a property before its set? Or please share more details. Also, why are you trying to create new ORM, where we can use doctrine with codeigniter easily?

Related

PHP 5.6: ArrayAccess: Function isset calls offsetGet and causes undefined index notice

I wrote simple PHP class that implements ArrayAccess Interface:
class MyArray implements ArrayAccess
{
public $value;
public function __construct($value = null)
{
$this->value = $value;
}
public function &offsetGet($offset)
{
var_dump(__METHOD__);
if (!isset($this->value[$offset])) {
throw new Exception('Undefined index: ' . $offset);
}
return $this->value[$offset];
}
public function offsetExists($offset)
{
var_dump(__METHOD__);
return isset($this->value[$offset]);
}
public function offsetSet($offset, $value)
{
var_dump(__METHOD__);
$this->value[$offset] = $value;
}
public function offsetUnset($offset)
{
var_dump(__METHOD__);
$this->value[$offset] = null;
}
}
It works normally in PHP 7, but the problem in PHP 5.6 and HHVM.
If I call function isset() on undefined index, the PHP will call offsetGet() instead of offsetExists() which will cause Undefined index notice.
In PHP 7, it calls offsetGet() only if offsetExists() returns true, so there is no error.
I think that this is related to PHP bug 62059.
The code is avalible at 3V4L, so you can see what is wrong. I added few more debug calls and throw exception if index is undefined because notices aren't shown in 3V4L:
https://3v4l.org/7C2Fs
There shouldn't be any notice otherwise PHPUnit tests will fail.
How can I fix this error?
It looks like this is a PHP bug in old versions of PHP and HHVM. Because PHP 5.6 is not supported anymore, this bug will not be fixed.
Quick fix is to add additional check in method offsetGet() and return null if index is undefined:
class MyArray implements ArrayAccess
{
public $value;
public function __construct($value = null)
{
$this->value = $value;
}
public function &offsetGet($offset)
{
if (!isset($this->value[$offset])) {
$this->value[$offset] = null;
}
return $this->value[$offset];
}
public function offsetExists($offset)
{
return isset($this->value[$offset]);
}
public function offsetSet($offset, $value)
{
$this->value[$offset] = $value;
}
public function offsetUnset($offset)
{
$this->value[$offset] = null;
}
}
See code at 3V4L and zerkms's comments (first, second, third).

How do I fix my illegal offset?

I've been trying to make this code work, but (with my small knowledge of coding) I can't seem to. Any ideas on how to do this?
The error is as follows:
"Warning: Illegal offset type in isset or empty in C:\UwAmp\www\undersokning\classes\Session.php on line 4"
<?php
class Session {
public static function exists($name) {
return (isset($_SESSION[$name])) ? true : false;
}
public static function put($name, $value) {
return $_SESSION[$name] = $value;
}
public static function get($name) {
return $_SESSION[$name];
}
public static function delete($name) {
if(self::exists($name)) {
unset($_SESSION[$name]);
}
}
}

PHP: Get Acces To Private Variable In Class

I've been doing a project in PHP for the last few hours and I have encountered into a problem.
The problem is I don't know how to access private variables in a class and I can't find it online.
Example:
<?php
class Example{
private $age;
public function __construct() {
$age = 14;
$this->checkAge();
}
private function checkAge() {
if($this->$age > 12)
echo "welcome!";
}
}
$boy = new Example();
?>
As far as I know, I should be able to access the variable with $this->$age but it isn't working.
Thank you.
EDIT: Got it working with help of the awesome stackoverflooooooooow community, this is how a working one looks.
<?php
class Example{
private $age;
public function __construct() {
$this->age = 14;
$this->checkAge();
}
private function checkAge() {
if($this->age > 12)
echo "welcome!";
}
}
$boy = new Example();
?>
Look at this approach.
first: create Entity that stores and retrieves data inside of private $attributes array, and with magic __set(), __get() You can also do like: $object->variable = 123
second: extend Entity with Human class and add some function specific to child class (for example hasValidAge()):
<?php
class Entity {
private $attributes;
public function __construct($attributes = []) {
$this->setAttributes($attributes);
}
public function setAttribute($key, $value) {
$this->attributes[$key] = $value;
return $this;
}
public function setAttributes($attributes = []) {
foreach($attributes AS $key => $value) {
$this->setAttribute($key, $value);
}
}
public function getAttribute($key, $fallback = null) {
return (isset($this->attributes[$key]))?
$this->attributes[$key] : $fallback;
}
public function __get($key) {
return $this->getAttribute($key);
}
public function __set($key, $value) {
$this->setAttribute($key, $value);
}
}
class Human extends Entity {
public function __construct($attributes = []) {
$this->setAttributes($attributes);
$this->checkAge();
}
public function hasValidAge() {
return ($this->getAttribute('age') > 12)? true : false;
}
}
$boy = new Human(['name' => 'Mark', 'age' => 14]);
if($boy->hasValidAge()) {
echo "Welcome ".$boy->name."!";
}
?>
p.s. I've removed echo "Welcome!" part from constructor because it's not cool to do echo from model object, in our example Human is model of Entity.

PHP Observer Pattern, Issue

Bellow is a PHP script.
I tried to implement the Observer pattern (without MVC structure)... only basic.
The error which is encountered has been specified in a comment.
First I tried to add User objects to the UsersLibrary repository. There was a error such as User::update() does not exists or something.
Why is that error encountered? What fix should be applied and how?
interface IObserver {
public function update(IObservable $sender);
}
interface IObservable {
public function addObserver(IObserver $obj);
public function notify();
}
class UsersLibrary implements IObservable {
private $container;
private $contor;
//private $z;
public function __construct() {//IObserver $a) {
$this->container = array();
$this->contor = 0;
echo "<div>[constructing UsersLibrary...]</div>";
$this->addObserver(new Logger());
//$this->z = $a;
}
public function add($obj) {
echo "<div>[adding a new user...]</div>";
$this->container[$this->contor] = $obj;
$this->contor++;
$this->notify();
}
public function get($index) {
return $this->container[$index];
}
public function addObserver(IObserver $obj) {
$this->container[] = $obj;
}
public function notify() {
echo "<div>[notification in progress...]</div>";
foreach($this->container as $temp) {
//echo $temp;
#################################################################
$temp->update(); //--------ERROR
//Fatal Error: Call to a member function update() on a non-object.
#################################################################
}
//$this->container[0]->update();
//$this->z->update($this);
}
}
class User {
private $id;
private $name;
public function __construct($id, $name) {
$this->id = $id;
$this->name = $name;
}
public function getId() {
return $this->id;
}
public function getName() {
return $this->name;
}
}
class Logger implements IObserver {
public function __construct() {
echo "<div>[constructing Logger...]</div>";
}
public function update(IObservable $sender) {
echo "<div>A new user has been added.</div>";
}
}
$a = new UsersLibrary(); //new Logger());
//$a->add(new User(1, "DemoUser1"));
//$a->add(new User(2, "DemoUser2"));
$a->add("Demo");
echo $a->get(0);
//echo $a->get(0)->getName();
Your User class is not implementing interface IObserver and therefore is not forced to have the method update().
You have to instantiate a new User() in order to add it to the UsersLibrary:
$library = new UsersLibrary();
$user = new User(1, "Demo");
$library->add($user);
Also, you are mixing Users and Loggers into your UsersLibrary container. Maybe think about separating the containers for them?
You are passing a string instead of an object in your $a->add() call. You should either pass in an object, or alter the code in UserLibrary::add() to wrap it's argument in an appropriate object (or do an object lookup of it sees a string, for instance find a user with that name).
$user = new User(1, "Demo");
$a = new UsersLibrary();
$a->add($user);

CodeIgniter session object cannot be found

I'm working on a model that tracks user data and stores it in a session, where appropriate. Here's the basic structure of it:
public function __construct() {
parent::__construct();
$this->load->database();
$this->load->library('session');
if (!is_null($this->session->userdata('user'))) {
$arrData = $this->session->userdata('user');
$this->_netID = $arrData['_netID'];
$this->_fName = $arrData['_fName'];
$this->_eventMgr = $arrData['_eventMgr'];
$this->_accessMgr = $arrData['_accessMgr'];
$this->_accessAcnt = $arrData['_accessAcnt'];
$this->_accessEvnt = $arrData['_accessEvnt'];
$this->_accessCMS = $arrData['_accessCMS'];
$this->_accessReg = $arrData['_accessReg'];
$this->_accessRep = $arrData['_accessRep'];
$this->_accessPay = $arrData['_accessPay'];
$this->_okEvents = $arrData['_okEvents'];
}
}
public function __get($name) {
switch($name) {
default:
if (function_exists('parent::__get')) {
return parent::__get($name);
} else {
return $this->$name;
}
}
}
public function __set($name,$val) {
switch($name) {
default:
if (function_exists('parent::__set')) {
return parent::__set($name,$val);
} else {
$this->$name = $val; }
}
}
The issue I'm having is right in the constructor. Whenever it hits the seventh line (checking if the user key is null) it errors out, saying:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: SessionUser::$session
Filename: models/sessionuser.php
Line Number: 83
Fatal error: Call to a member function userdata() on a non-object in /usr/cwis/data/www-data/melioraweekenddev/system/application/models/sessionuser.php on line 38
Any ideas on why?
My guess is you're trying to load a library from within a model which is not directly possible.
Try instead:
public function __construct() {
parent::__construct();
$CI =& get_instance(); //Loads the codeigniter base instance (The object your controller is extended from. & for php4 compatibility
$CI->load->database();
$CI->load->library('session');
if (!is_null($CI->session->userdata('user'))) {
...

Categories