PHP change variables from static function - php

I have started to build this class, and I want to register a user:
<?php
class User {
protected $_id;
protected $_name;
protected $_email;
protected $_password;
public $isLogged = false;
public $errors = array();
public function __construct() {
}
public static function register($username,$email,$password,$captcha,$agree) {
$user = new self;
array_push($user->errors,'Error!');
}
}
I call it like this:
$user = User::register($_POST['username'],$_POST['email'],$_POST['password'],$captcha,$agree);
if(empty($user->errors)) {
echo 'Success';
} else {
echo 'Failed';
}
Why does it returns Success? I did array_push!

class User {
// ...
public static function register($username,$email,$password,$captcha,$agree) {
$user = new self;
array_push($user->errors,'Error!');
return $user;
}
}
You forgot to return the $user object from register().

Related

Php, is it OK to use traits for DI?

consider this example:
class MyClass
{
public function doSomething()
{
$this->injected->getIt();
}
}
so far so simple (apart from injected is not injected). So, in full version:
class MyClass
{
/**
* #var Injected
*/
private $injected;
public function __constructor(Injected $injected)
{
$this->injected = $injected;
}
public function doSomething()
{
$this->injected->getIt();
}
}
but I find it enoromous. Why to pollute my class with tons of code of DI? Lets split this into two entities:
trait MyClassTrait
{
/**
* #var Injected
*/
private $injected;
public function __constructor(Injected $injected)
{
$this->injected = $injected;
}
}
class MyClass
{
use MyClassTrait;
public function doSomething()
{
$this->injected->getIt();
}
}
its much nicer although I never seen anybody using it like this. Is it a good approach?
For example like this:
<?php
class Factory
{
private $services = [];
public function __construct() {
$this->services[self::class] = $this;
}
public function getByType($type){
if(isset($services[$type])){
return $services[$type];
}
if(class_exists($type)){
$reflection = new ReflectionClass($type);
$constructor = $reflection->getConstructor();
$parameters = [];
if($constructor)
foreach($constructor->getParameters() as $parameter){
if($parameter->getClass()) {
$parameters[] = $this->getByType($parameter->getClass()->name);
} else if($parameter->isDefaultValueAvailable()){
$parameters[] = $parameter->getDefaultValue();
}
}
return $services[$type] = $reflection->newInstanceArgs($parameters);
} // else throw Exception...
}
}
abstract class DI
{
public function __construct(Factory $factory) {
$reflection = new ReflectionClass(get_class($this));
foreach($reflection->getProperties() as $property){
preg_match('/#var ([^ ]+) #inject/', $property->getDocComment(), $annotation);
if($annotation){
$className = $annotation[1];
if(class_exists($className)){
$property->setAccessible(true);
$property->setValue($this, $factory->getByType($className));
} // else throw Exception...
}
}
}
}
class Injected
{
public function getIt($string){
echo $string.'<br />';
}
}
class DIByConstructor
{
/** #var Injected */
private $byConstructor;
public function __construct(Injected $injected) {
$this->byConstructor = $injected;
}
public function doSomething()
{
echo 'Class: '.self::class.'<br />';
$this->byConstructor->getIt('By Constructor');
echo '<br />';
}
}
class DIByAnnotation extends DI
{
/** #var Injected #inject */
private $byAnnotation;
public function doSomething()
{
echo 'Class: '.self::class.'<br />';
$this->byAnnotation->getIt('By Annotation');
echo '<br />';
}
}
class DIBothMethods extends DI
{
/** #var Injected */
private $byConstructor;
/** #var Injected #inject */
private $byAnnotation;
public function __construct(Factory $factory, Injected $injected) {
parent::__construct($factory);
$this->byConstructor = $injected;
}
public function doSomething()
{
echo 'Class: '.self::class.'<br />';
$this->byConstructor->getIt('By Constructor');
$this->byAnnotation->getIt('By Annotation');
echo '<br />';
}
}
$factory = new Factory();
$DIByConstructor = $factory->getByType('DIByConstructor');
$DIByConstructor->doSomething();
$DIByAnnotation = $factory->getByType('DIByAnnotation');
$DIByAnnotation->doSomething();
$DIBothMethods = $factory->getByType('DIBothMethods');
$DIBothMethods->doSomething();
Note that with #Kazz approaching (DI by Annotations) you cannot reference an Interface, instead you are referencing a Class. So this is good for fast instantiating with almost zero verbose but at the end, you are loosing all the DI potential.

PHP: How to make a function accept a single object which can be of different classes based on the call or user input?

Okay, here is my print_details function
class Vehicle{
//constructor goes here
public function print_details(//one object as parameter)
{
echo "\nName : $this->name";
echo "\nDescription: $this->desc \n";
if(strnatcasecmp(get_class($this),"Car")==0)
{
$this->getCarDetails();
}
elseif (strnatcasecmp(get_class($this),"Bus")==0)
{
$this->getBusDetails();
}
}
}
I intend to use only one object as a parameter, which can be of either class Car or Bus. But it should call the appropriate function based on the class of the object.
Is it possible to do it? If yes,how?
I would suggest you to use the following class structures:
abstract class Vehicle {
protected $name;
protected $desc;
abstract public function getDetails();
//constructor goes here
public function print_details()
{
echo "Name : $this->name", PHP_EOL;
echo "Description: $this->desc", PHP_EOL;
foreach ($this->getDetails() as $key => $value) {
echo "{$key}: {$value}", PHP_EOL;
}
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getDesc()
{
return $this->desc;
}
public function setDesc($desc)
{
$this->desc = $desc;
}
}
class Car extends Vehicle {
protected $type;
public function getType()
{
return $this->type;
}
public function setType($type)
{
$this->type = $type;
}
public function getDetails()
{
return [
'Type' => $this->type
];
}
}
class Bus extends Vehicle {
protected $numberOfSeats;
/**
* #return mixed
*/
public function getNumberOfSeats()
{
return $this->numberOfSeats;
}
/**
* #param mixed $numberOfSeats
*/
public function setNumberOfSeats($numberOfSeats)
{
$this->numberOfSeats = $numberOfSeats;
}
public function getDetails()
{
return [
'Number of seats' => $this->numberOfSeats
];
}
}
$car = new Car();
$car->setName('BMW');
$car->setDesc('Car description');
$car->setType('sedan');
$car->print_details();
$car = new Bus();
$car->setName('Mers');
$car->setDesc('Bus description');
$car->setNumberOfSeats(20);
$car->print_details();

PHP Dependency Injection issue

Ey guys, I am trying to learn Dependency Injection and I wrote this code:
class User {
public $id;
public function __construct($id) {
$this->id = $id;
}
public function getName() {
return 'Alex';
}
}
class Article {
public $author;
public function __construct(User $author) {
$this->author = $author;
}
public function getAuthorName() {
return $this->author->getName();
}
}
$news = new Article(10);
echo $news->getAuthorName();
However, I am getting WSOD. What had I done wrong in it ?
You have specified wrong instance.Use the code below
<?php
class User {
public $id;
public function __construct($id) {
$this->id = $id;
}
public function getName() {
return 'Alex';
}
}
class Article {
public $author;
public function __construct(User $author) {
$this->author = $author;
}
public function getAuthorName() {
return $this->author->getName();
}
}
$news = new Article(new User(10));
echo $news->getAuthorName(); //Outputs Alex
Hope this helps you

Zf2 entity join

Can you help me? I can't understand how to join 2 and more tables, each table has the entity. Whether it is possible to use as in doctrine? I don't want to use doctrine.
How to join entities and use in views?
class User
{
protected $id;
protected $email;
protected $password;
public function getId()
{
return $this->id;
}
public function setId($value)
{
$this->id = $value;
}
public function setEmail($value)
{
$this->email = $value;
}
public function getEmail()
{
return $this->email;
}
public function setPassword($value)
{
$this->password = $value;
}
public function getPassword()
{
return $this->password;
}
}
class Info
{
protected $id;
protected $lastname;
protected $firstname;
public function getId()
{
return $this->id;
}
public function setId($value)
{
$this->id = $value;
}
public function setLastname($value)
{
$this->lastname = $value;
}
public function getLastname()
{
return $this->lastname;
}
public function setFirstname($value)
{
$this->firstname = $value;
}
public function getFirstname()
{
return $this->firstname;
}
}
class User
{
...
protected $info;
...
public function readInfo()
{
return $this->info;
}
public function writeInfo(Info $entity)
{
$this->info = $entity;
return $this;
}
}
class ModelUser
{
public function get()
{
$query = 'query for user with info';
$adapter = Zend\Db\TableGateway\Feature\GlobalAdapterFeature::getStaticAdapter();
$result = $adapter->query($query, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
/* Or use tableGateway */
/* Class methods hydrator */
$hydrator = new \Zend\Stdlib\Hydrator\ClassMethods;
/* Hydrate User entity from result */
$userEntity = $hydrator->hydrate($result->toArray(), new User);
/* Hydrate Info entity from result */
$infoEntity = $hydrator->hydrate($result->toArray(), new Info);
/* Write Info entity to User entity */
$userEntity->writeInfo($infoEntity);
return $userEntity;
}
}
class UserController
{
public function indexAction()
{
$model = new ModelUser();
$userEntity = $model->get();
return array(
'user' => $userEntity
);
}
}

How to access variable of one class from other class?

I have situation like this:
// Object Class
class Person_Object {
protected $_id;
public function __construct( $id = null ) {
$this->_id = $id;
}
public function getMapper() {
$mapper = new Person_Mapper();
return $mapper;
}
public function printIdInMapper() {
$this->getMapper()->printIdInMapper();
}
}
// Mapper Class
class Person_Mapper {
public function printIdInMapper() {
// How to access Person_Object's id here and echo id?
}
}
// Code
$personModel = new Person_Object(10);
$personModel->printIdInMapper(); // should print 10
Now how to echo Person_Object's id value 10 in printIdInMapper() function here
Try this:
// Object Class
class Person_Object {
protected $_id;
public function __construct( $id = null ) {
$this->_id = $id;
}
public function getId() {
return $this->_id;
}
public function getMapper() {
$mapper = new Person_Mapper($this);
return $mapper;
}
public function printIdInMapper() {
$this->getMapper()->printIdInMapper();
}
}
// Mapper Class
class Person_Mapper {
$_person
public function __construct( $person ) {
$this->_person = $person
}
public function printIdInMapper() {
echo $this->_person->getId();
}
}
A slightly different approach:
class Person_Object {
protected $_id;
public function __construct( $id = null ) {
$this->_id = $id;
}
public function getId() {
return $this->_id;
}
public function getMapper() {
$mapper = new Person_Mapper();
$mapper->setPerson($this);
return $mapper;
}
public function printIdInMapper() {
$this->getMapper()->printIdInMapper();
}
}
// Mapper Class
class Person_Mapper {
protected $person;
public function setPerson(Person_Object $person) {
$this->person = $person;
}
public function getPerson() {
return $this->person;
}
public function printIdInMapper() {
echo $this->getPerson()->getId();
}
}

Categories