Class doesn't fetch correctly the object's values - php

Given this class :
class Address {
public $id;
public $id_easypost;
public $street1;
public $street2;
public function __construct($id,$id_easypost,$street1,$street2) {
$this->$id = $id;
$this->$id_easypost = $id_easypost;
$this->$street1 = $street1;
$this->$street2 = $street2;
}
}
I don't get why, when creating an object like that:
$ad = new Address("1", "2", "3", "4");
Values are not "fetched" correctly :
object(Address)[15]
public 'id' => null
public 'id_easypost' => null
public 'street1' => null
public 'street2' => null
public '1' => string '1' (length=1)
public '2' => string '2' (length=1)
public '3' => string '3' (length=1)
public '4' => string '4' (length=1)
However, this class works correctly :
class Rider {
public $id;
public $name;
public $activated;
public $created_at;
public $updated_at;
public function __construct($id, $name, $activated, $created_at, $updated_at) {
$this->id = $id;
$this->name = $name;
$this->activated = $activated;
$this->created_at = $created_at;
$this->updated_at = $updated_at;
}
}
And "fetch" the values correctly.
object(Rider)[16]
public 'id' => string '1' (length=1)
public 'name' => string '2' (length=1)
public 'activated' => string '3' (length=1)
public 'created_at' => string '4' (length=1)
public 'updated_at' => string '5' (length=1)
How is that ?

You shouldn't use $ sign to access object properties. This is correct:
$this->id = $id;

Related

How to mysqli_result::fetch_array with key [table.attribute] in the array?

I'm trying to create a general method to automatically instantiate objects from a query like this:
SELECT town.*, content.*, user.*
FROM townhub.content
LEFT JOIN town ON content.townReceiver = town.id_town
LEFT JOIN user ON content.author = user.id_user
The method that I want to build should return 3 type of objects: Town, User and Content into an array. I thought on something like that:
protected function build_objects($result, Array $classes) {
$data = array();
$i = 0;
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
foreach ($classes as $class) {
$$class = new $class;
$$class = $$class->fill_object($$class, $row);
$data[$i][$class] = $$class;
}
$i++;
}
return $data;
}
And then, in each class, a method like that:
public function fill_object($object, Array $row) {
$attributes = get_object_vars($object);
foreach ($row as $attribute => $value) {
foreach ($attributes as $objAtt => $emptyValue) {
if ($attribute == $objAtt) {
$object->$attribute = $value;
}
}
}
return $object;
}
Actually, this is doing what I want, the following array (was printed using using var_dump($data) in build_objects() ):
array (size=4)
0 =>
array (size=3)
'Content' =>
object(Content)[4]
protected 'id_content' => string '1' (length=1)
public 'title' => string 'Hello World!' (length=10)
public 'description' => string 'Hello world description' (length=43)
public 'category' => string '1' (length=1)
public 'date' => string '2015-01-01' (length=10)
public 'townReceiver' => string '1' (length=1)
public 'author' => string '1' (length=1)
private 'dbHost' (Model) => string 'localhost' (length=9)
private 'dbUser' (Model) => string 'root' (length=4)
private 'dbPass' (Model) => string 'root' (length=4)
private 'dbName' (Model) => string 'townhub' (length=7)
private 'conn' (Model) => null
'Town' =>
object(Town)[5]
protected 'id_town' => string '1' (length=1)
public 'name' => string 'Isaac' (length=5)
public 'population' => string '750' (length=3)
private 'dbHost' (Model) => string 'localhost' (length=9)
private 'dbUser' (Model) => string 'root' (length=4)
private 'dbPass' (Model) => string 'root' (length=4)
private 'dbName' (Model) => string 'townhub' (length=7)
private 'conn' (Model) => null
'User' =>
object(User)[6]
protected 'id_user' => string '1' (length=1)
protected 'dni' => string '20011225' (length=9)
private 'password' => string '1234' (length=4)
public 'name' => string 'Isaac' (length=5)
public 'firstSurname' => string 'Surname1' (length=5)
public 'secondSurname' => string 'Surname2' (length=5)
public 'birthdate' => string '0000-00-00' (length=10)
public 'gender' => string 'H' (length=1)
public 'email' => string 'isaac#mail.com' (length=19)
public 'isAdmin' => string '1' (length=1)
public 'id_town' => string '1' (length=1)
private 'dbHost' (Model) => string 'localhost' (length=9)
private 'dbUser' (Model) => string 'root' (length=4)
private 'dbPass' (Model) => string 'root' (length=4)
private 'dbName' (Model) => string 'townhub' (length=7)
private 'conn' (Model) => null
The problem is that when I fech_array (in fill_object() method) town's names are overridden by user's names; so I can't get the town's name. The easy solution is to change attribute's names on db and classes; but I think that will be a bad solution...
Keep in mind that attribute's names should be equals on db and classes, so alias in the query is not possible.
There are any way to get with fetch_array an Array with key [table.attribute] instead [attribute]?
I would also like to know better ways to do this if what I want to do is not possible.
<?php
class DataCollectionHelper
{
/**
* $result var is the result of:
* "SELECT *
* FROM townhub.content".
*
* As you left join your tables, it may appear that you haven't any towns and users
* for particular content.
*
* #param $result
*
* #return array
*/
protected function build_objects($result)
{
$data = array();
$i = 0;
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$contentObject = new Content();
$contentObject->fill_object($row);
$data[$i]['Content'] = $contentObject;
$data[$i]['User'] = $this->getUserByContentAuthor($contentObject->getAuthor());
$data[$i]['Town'] = $this->getTownByContentByTownReceiver($contentObject->getTownReceiver());
$i++;
}
return $data;
}
/**
* #param integer $townReceiver
*
* #return Town
*/
private function getTownByContentByTownReceiver($townReceiver)
{
/**
* Here you have to get town data by your $townReceiver - property
* and return the object of Town
*/
}
/**
* #param integer $author
*
* #return User
*/
private function getUserByContentAuthor($author)
{
/**
* The same here for users
*/
}
}
class Content
{
/**
* #var integer
*/
protected $content_id;
/**
* #var string
*/
public $title;
/**
* #var integer
*/
public $townReceiver;
/**
* #var string
*/
public $description;
/**
* #var integer
*/
public $author;
/* other vars */
/**
* #param array $row
*
* #return $this
*/
public function fill_object(array $row)
{
/*
* It's not the best approach, to do like that.
* It's better to use setters or just set your properties
* $this->title = $row['title']; etc
*
* Still you could use $this instead of your $object variable
*/
$attributes = get_object_vars($this);
foreach ($row as $attribute => $value) {
foreach ($attributes as $objAtt => $emptyValue) {
if ($attribute == $objAtt) {
$this->$attribute = $value;
}
}
}
return $this;
}
/**
* #return int
*/
public function getTownReceiver()
{
return $this->townReceiver;
}
/**
* #return int
*/
public function getAuthor()
{
return $this->author;
}
}

Accessing object properties in PHP

I am trying to access properties of a custom object in PHP:
<?php
namespace App\Classes;
use Illuminate\Database\Eloquent\Model;
class AED extends Model {
protected $table = 'aeds';
protected $fillable = ['owner', 'street', 'postal_code', 'locality', 'latitude', 'longitude', 'annotation_type'];
public $timestamps = true;
public $id;
public $owner;
public $object;
public $street;
public $postalCode;
public $locality;
public $latitude;
public $longitude;
public $annotation_type;
public $distance;
public function set($data) {
foreach ($data as $key => $value) {
if(property_exists($this, $key)) {
$this->$key = $value;
}
}
}
}
The code to access these properties:
<?php
namespace App\Transformer;
use App\Classes\AED;
use League\Fractal\TransformerAbstract;
class AEDTransformer extends TransformerAbstract {
public function transform(AED $aed) {
return [
'data' => $aed->owner
];
}
}
When I call the function, I get this as a response:
{
data: [
{
data: null
}
],
meta: "TestMeta"
}
The strange thing is, when I just var_dump the object I get the full info:
...
protected 'original' =>
array (size=11)
'id' => int 1
'owner' => string 'Owner 1' (length=7)
'object' => string 'Object 1' (length=8)
'street' => string 'Street 1' (length=8)
'postal_code' => string '11111' (length=5)
'locality' => string 'Locality 1' (length=10)
'latitude' => float 100
'longitude' => float 100
'annotation_type' => string '1' (length=1)
'created_at' => string '0000-00-00 00:00:00' (length=19)
'updated_at' => string '0000-00-00 00:00:00' (length=19)
...
So the data can be taken from the database as expected and is being received as well. Why does the accessing not work then and I receive a "null".
I use the "set" method inside the custom function here:
class AEDHelper {
static public function searchAED($position) {
$var1 = $position['latitude'];
$var2 = $position['longitude'];
$var3 = $position['latitude'];
$queryResults = DB::select(DB::raw("SQLCODE"));
$results = [];
foreach ($queryResults as $results) {
$aed = new AED();
$aed->set($results);
$results[] = $aed;
}
return $results;
}
Here I create a new AED() instance. So I would guess I need to define the object properties therefore as now not Eloquent will be used but a custom AED class needs to be instantiated for displaying SQL results.
Best
you don't have to define fields in your model. Eloquent makes them available dynamically.
if you want to fill those fields you can without having them in your model. because the field will be available if you try to set a value for it.
here is how
$aed = new AED;
$aed->owner = "The Owner";
$aed->object = "The Object";
....
....
....
$aed->save();
or this will work as well
AED::create([
'owner' => "The Owner",
'object' => "The Object",
.....
.....
.....
]);
or if you want update an existing model.
$aed = AED::find(1);
// change owner
$aed->owner= "New Owner";
$aed->save();

find out a class variable's defined scope (from within the class)

Given:
class myClass extends \Phalcon\Mvc\Model
{
public $a;
protected $b;
private $c;
}
How can I test that $a is public, $b is protected, and $c is private from within myClass?
You can use ReflectionProperty -
class myClass
{
public $a;
protected $b;
private $c;
}
$obj = new myClass();
$reflect_a = new ReflectionProperty(get_class($obj), 'a');
$reflect_c = new ReflectionProperty(get_class($obj), 'c');
var_dump($reflect_a->isProtected());
var_dump($reflect_c->isPrivate());
Depending on the result you can hide or show them.
For your needs you can use use Models Meta-Data. You can get the attributes of the model within the model:
<?php
/**
* Posts Model
*
*/
class Posts extends \Phalcon\Mvc\Model
{
public $id;
public $users_id;
public $categories_id;
public $title;
public $slug;
public $content;
public $number_views;
public $number_replies;
public $votes_up;
public $votes_down;
public $sticked;
public $modified_at;
public $created_at;
public $edited_at;
public $status;
public $locked;
public $deleted;
public $accepted_answer;
private $foo_bar;
}
Somewhere in the controller:
var_dump($this->modelsMetadata->getAttributes(new Posts()));die;
Output:
array (size=18)
0 => string 'id' (length=2)
1 => string 'users_id' (length=8)
2 => string 'categories_id' (length=13)
3 => string 'title' (length=5)
4 => string 'slug' (length=4)
5 => string 'content' (length=7)
6 => string 'number_views' (length=12)
7 => string 'number_replies' (length=14)
8 => string 'votes_up' (length=8)
9 => string 'votes_down' (length=10)
10 => string 'sticked' (length=7)
11 => string 'created_at' (length=10)
12 => string 'modified_at' (length=11)
13 => string 'edited_at' (length=9)
14 => string 'status' (length=6)
15 => string 'locked' (length=6)
16 => string 'deleted' (length=7)
17 => string 'accepted_answer' (length=15)
Also you can create an model's method:
public function getAttributes()
{
$metaData = $this->getModelsMetaData();
return $metaData->getAttributes($this);
}
\Phalcon\Mvc\Model\MetaData::getAttributes Returns table attributes names - fields of table.
Also PHP's get_class_vars() returns an array of all properties visible in the current scope. In your case it should return all public properties.

yii2 find returns null

Why does findone() returns all public property as null.
class User extends \yii\db\ActiveRecord
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
$result = static::findOne(['username' => $username]);
var_dump($result);
return $result;
}
This returns
object(app\models\User)[81]
public 'id' => null
public 'username' => null
public 'password' => null
public 'authKey' => null
public 'accessToken' => null
private '_attributes' (yii\db\BaseActiveRecord) =>
array (size=6)
'id' => int 1
'username' => string 'admin' (length=5)
'password' => string '123456' (length=6)
'auth_key' => string 'jkkk' (length=4)
'created' => null
'modified' => null
You should simply remove db attributes from your model :
class User extends \yii\db\ActiveRecord
{
public static function findByUsername($username)
{
....
Yii automatically defines an attribute in Active Record for every column of the associated table. You should NOT redeclare any of the attributes.
Read more : http://www.yiiframework.com/doc-2.0/guide-db-active-record.html

How to get datas from related tables in Phalcon?

I have exactly the same structure like in the phalcon models documentation:
http://docs.phalconphp.com/en/latest/_images/eer-1.png
In the models I implemented the following hasmany and belongsto lines:
Robots model:
class Robots extends \Phalcon\Mvc\Model
{
public $id;
public $name;
public function initialize(){
$this->hasMany("id", "RobotsParts", "robots_id");
}
}
Parts model:
class Parts extends \Phalcon\Mvc\Model
{
public $id;
public $name;
public function initialize(){
$this->hasMany("id", "RobotsParts", "parts_id");
}
}
RobotParts model:
class RobotsParts extends \Phalcon\Mvc\Model
{
public $id;
public $robots_id;
public $parts_id;
public function initialize(){
$this->belongsTo("robots_id", "Robots", "id");
$this->belongsTo("parts_id", "Parts", "id");
}
}
At this point I was hoping to get all the data by calling RobotParts::find(), but I can see only the id's.
For debuging I dumped, but find only the ids:(
$rp = RobotParts::find()->toArray();
var_dump($rp);
I would like to get something like this as result:
array (size=1)
0 =>
array (size=7)
'id' => int '1' (length=1)
'robots_id' => int '4' (length=1)
'name' => string 'r2d2' (length=4)
'type' => string 'droid' (length=5)
'year' => int '2184' (length=4)
'parts_id' => int '4' (length=1)
'name' => string 'wheel' (length=5)
var_dump() does not contains the related tables, needed to reference to it from view like:
robots.RobotParts.name

Categories