Zf2 entity join - php

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
);
}
}

Related

SQL request or php solution to manage employers

My entity :
class User{
id : int
name : string
boss : User()
}
I want to create a function that return an array() of users that work under a giving user.
example :
public function MyEmployers( User $user , array $usersList )
{
$myEmployers = array();
...
return $myEmployers;
}
$results = $this->myEmployers ( $employer1 , $allEmployers)
dump ( $results );
$results = [ 4 , 5 , 6 ];
I found a solution if someone can improve it feel free :
public $tree = array();
public function MyEmployers(User $user)
{
$superior_key_id = array();
$all_users = $this->getallusers();
$id = $user->getId();
foreach ($all_users as $user) {
if ($user->getSuperior())
$superior_key_id[$user->getSuperior()->getId()][] = $user;
}
$this->getSubEmployee($this->getUser(), $superior_key_id);
return ($this->tree);
}
public function getSubEmployee($user, $superior_key_id)
{
if (isset($superior_key_id[$user->getId()])) {
foreach ($superior_key_id[$user->getId()] as $user) {
$this->tree[] = $user;
$this->getSubEmployee($user, $superior_key_id);
}
}
return $user;
}
this one will get all bosses if you're interested :
public function MyBosses(User $user)
{
$bosses = array();
while ($user->getSuperior()) {
array_push($bosses, $user->getSuperior());
$user = $user->getSuperior();
}
return $bosses;
}
You could set up a one-to-many relationship between boss and employee
So you're user class could look like:
class User{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string")
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="employee")
*/
private $boss;
/**
* #ORM\OneToMany(targetEntity="App\Entity\User", mappedBy="boss")
*/
private $employees;
public function __construct()
{
$this->employees = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
/**
* #return Collection|employees[]
*/
public function getEmployees(): Collection
{
return $this->employees;
}
public function addEmployee(employee $employee): self
{
if (!$this->employees->contains($employee)) {
$this->employees[] = $employee;
}
return $this;
}
public function removeEmployee(employee $employee): self
{
if ($this->employees->contains($employee)) {
$this->employees->removeElement($employee);
}
return $this;
}
public function getBoss(): ?Usesr
{
return $this->boss;
}
public function setBoss(?User $boss): self
{
$this->boss = $boss;
return $this;
}
}
You would need to set up the database relationship with the symfony make:entity command.
To get all employeers under a user, you could do something like:
function getAllEmployeesUnder(User $user)
{
$allEmployees = [];
foreach ($user->getEmployees as $employee) {
$allEmployees[] = $employee;
$allEmployees = array_merge($allEmployees, $this->getAllEmployeesUnder($employee));
}
return $allEmployees;
}

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 Zend Framework serialize array of objects

I have a shopping cart class that I wish to serialize to store in a session variable.
My cart class is
namespace Application\Model\Cart;
use Application\Model\AbstractModel;
use Zend\ServiceManager\ServiceManager;
use Application\Model\Cart\Product;
use Application\Model\Cart\ProductOptions;
use Application\Entity\Products;
class Cart extends AbstractModel
{
protected $products;
protected $totalIncVat;
protected $totalExVat;
public function __construct(ServiceManager $serviceManager = NULL)
{
parent::__construct($serviceManager);
$this->products = array();
$product = new Product();
$product->setProductId(1);
$option = new ProductOptions();
$product->addOption($option);
$this->products[] = $product;
}
public function __sleep()
{
return $this->products;
}
}
As can be seen in the constructor I am adding a test product and product option. The product classes are stored in an array $this->products.
My products class is
namespace Application\Model\Cart;
use Application\Model\Cart\ProductOptions;
class Product
{
protected $productId;
protected $title;
protected $priceEachIncVat;
protected $priceEachVat;
protected $vat;
protected $qty;
protected $total;
protected $options;
public function __construct()
{
$this->options = array();
}
public function getProductId()
{
return $this->productId;
}
public function getTitle()
{
return $this->title;
}
public function getPriceEachIncVat()
{
return $this->priceEachIncVat;
}
public function getPriceEachVat()
{
return $this->priceEachVat;
}
public function getVat()
{
return $this->vat;
}
public function getQty()
{
return $this->qty;
}
public function getTotal()
{
return $this->total;
}
public function getOptions()
{
return $this->options;
}
public function setProductId($productId)
{
$this->productId = $productId;
return $this;
}
public function setTitle($title)
{
$this->title = $title;
return $this;
}
public function setPriceEachIncVat($priceEachIncVat)
{
$this->priceEachIncVat = $priceEachIncVat;
return $this;
}
public function setPriceEachVat($priceEachVat)
{
$this->priceEachVat = $priceEachVat;
return $this;
}
public function setVat($vat)
{
$this->vat = $vat;
return $this;
}
public function setQty($qty)
{
$this->qty = $qty;
return $this;
}
public function setTotal($total)
{
$this->total = $total;
return $this;
}
public function setOptions(Array $options)
{
$this->options = $options;
return $this;
}
public function addOption(ProductOptions $option)
{
$this->options[] = $option;
return $this;
}
}
And finally my product options class is
namespace Application\Model\Cart;
class ProductOptions
{
protected $optionId;
protected $name;
protected $price;
protected $valueId;
protected $value;
public function getOptionId()
{
return $this->optionId;
}
public function getName()
{
return $this->name;
}
public function getPrice()
{
return $this->price;
}
public function getValueId()
{
return $this->valueId;
}
public function getValue()
{
return $this->value;
}
public function setOptionId($optionId)
{
$this->optionId = $optionId;
return $this;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function setPrice($price)
{
$this->price = $price;
return $this;
}
public function setValueId($valueId)
{
$this->valueId = $valueId;
return $this;
}
public function setValue($value)
{
$this->value = $value;
return $this;
}
}
The problem I am having is that the classes are not serializing properly.
$serializer = new \Zend\Serializer\Adapter\PhpSerialize();
$serialized = $serializer->serialize($cart);
$cart = $serializer->unserialize($serialized);
When I remove the test product from the cart constructor all works well. The array of products is causing the problem.
The error I am getting is unserialize(): Error at offset 40 of 41 bytes.
The serialized string returned is
O:27:"Application\Model\Cart\Cart":1:{N;}
Does anyone know what I am missing?
Many thanks in advance.
I figured it out. The sleep magic method in cart class should contain return array('products');

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

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