PHP - dynamiclly set array params to extended class - php

In my PHP project, I'm implementing PHP through OOP.
I have class A which defines hardcoded path string and an array of params.
Class B extends class A and in __construct() method, I define that path and also define two parameters that I want to pass.
In my prepare() method I don't know how to dynamically set those two params so I can get them when calling $this->classB->getParams() method.
abstract class A
{
public function __construct(
private string $path,
private array $params
) {
}
public function getPath(): string
{
return $this->path;
}
public function getParams(): array
{
return $this->params;
}
public function setParams(?array $params)
{
$this->params = $params;
}
.
class B extends A
{
private ?string $name;
private ?string $address;
public function __construct(?string $name = null, ?string $address = null )
{
$this->name = $name;
$this->address = $address;
parent::__construct(
'path/to/some/file',
[
'name' => $name,
'address' => $address
]
);
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name)
{
$this->name = $name;
return $this;
}
public function getAddress(): ?string
{
return $this->address;
}
public function setAddress(?string $address)
{
$this->address = $address;
return $this;
}
}
..
class C
{
public function __construct(B $classB) {
$this->classB = $classB;
}
public function prepare()
{
$arrayParams = ["John Doe", "Forgotten Lane 007"];
$this->classB->setParams(arrayParams);
$path = $this->classB->getPath();
$params = $this->classB->getParams();
$c = new B('', ''); //?
$this->execute($path, $params);
}
Result is:
array(2) {
[0]=>
string(8) "John Doe"
[1]=>
string(18) "Forgotten Lane 007"
}
and I want:
array(2) {
["name]=>
string(8) "John Doe"
["address"]=>
string(18) "Forgotten Lane 007"
}
As I defined it in B class.
The example posted here: https://3v4l.org/msoSh
I am new to PHP so help with this will be appreciated. Thanks

Related

How to select from a database using getter and setter methods in PHP

I need to select/insert data from/to database using getter and setter methods. What I'm trying to achieve for now is to select everything from the db and echo it out in html, to see if I'm receiving anything at all.
This the code so far:
class Products extends DbConnect {
protected $id;
protected $sku;
protected $name;
protected $price;
protected $type;
protected $attributes;
public function select() {
$query = "SELECT * FROM products";
$result = $this->connect()->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC);
$this->id = $row['Id'];
$this->sku = $row['SKU'];
$this->name = $row['Name'];
$this->price = $row['Price'];
$this->type = $row['Type'];
$this->attributes = $row['Attributes'];
}
public function getId() {
return $this->id;
}
public function getSKU() {
return $this->sku;
}
public function getName() {
return $this->name;
}
public function getPrice() {
return $this->price;
}
public function getType() {
return $this->type;
}
public function getAttributes() {
return $this->attributes;
}
}
I'm not sure what I have to do next. I tried to see if I get any data like this:
public function __construct($name) {
$this->name = $name;
}
$product = new Products();
echo $product->name;
It tells me I'm not passing any arguments. Do I have to do something else with the selected data before I print it out? I'm completely new to this approach and I'm not really sure what to do.
Your constructor needs to be in the class
class Products extends DbConnect {
protected $id;
protected $sku;
protected $name;
protected $price;
protected $type;
protected $attributes;
public function __construct($name) {
$this->name = $name;
}
public function select() {
$query = "SELECT * FROM products";
$result = $this->connect()->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC);
$this->id = $row['Id'];
$this->sku = $row['SKU'];
$this->name = $row['Name'];
$this->price = $row['Price'];
$this->type = $row['Type'];
$this->attributes = $row['Attributes'];
}
public function getId() {
return $this->id;
}
public function getSKU() {
return $this->sku;
}
public function getName() {
return $this->name;
}
public function getPrice() {
return $this->price;
}
public function getType() {
return $this->type;
}
public function getAttributes() {
return $this->attributes;
}
}
Then you pass the parameters when you define the new class
$product = new Products("Product Name");
echo $product->name;
One thing I would suggest would be to change the constructor to accept an array that way you can pass any number of parameters across and order doesn't matter.
public function __construct(array $config = []) {
$this->name = $config["name"];
$this->id = $config["id"];
}
And then you can send any number of arguments through like this
$options = [
"name" => "ProductName",
"id" => "ProductID"
];
$product = new Products($options);
echo "Name: ".$product->name;
echo "ID: ".$product->id;

How can I copy an object of another class?

I have a class that extends of another one.
Class Test
class Test
{
private $id;
private $name;
private $age;
private $number;
public function getId() {
return $this->id;
}
public function setId($id) {
$this->id = $id;
return $this;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
return $this;
}
public function getAge() {
return $this->age;
}
public function setAge($age) {
$this->age = $age;
return $this;
}
public function getNumber() {
return $this->number;
}
public function setNumber($number) {
$this->number = $number;
return $this;
}
}
Class TestCopy
use Test;
class TestCopy extends Text
{
}
And then I have an object of the class Test:
$object = new Test();
$object->setId = 1;
$object->setName = Tom;
$object->setAge = 20;
$object->setNumber = 10;
How I can create an object of the class TestCopy (that will have the same attributes), and clone all the values of the object $object?
I tried with clone:
$objectCopy = clone $object;
But the object $objectCopy have to instance the class TestCopy, and when I clone, it instance the class Test.
And I tried so too:
foreach (get_object_vars($object) as $key => $name) {
$objectCopy->$key = $name;
}
But the attributes are private and when I call the function get_object_vars it returns null.
Any idea? Thank very much!
try this, Once you instantiate a object, you can't change the class (or other implementation details)
You can simulate it like so:
<?php
class Test
{
private $id;
private $name;
private $age;
private $number;
public function getId() {
return $this->id;
}
public function setId($id) {
$this->id = $id;
return $this;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
return $this;
}
public function getAge() {
return $this->age;
}
public function setAge($age) {
$this->age = $age;
return $this;
}
public function getNumber() {
return $this->number;
}
public function setNumber($number) {
$this->number = $number;
return $this;
}
public function toArray()
{
return get_object_vars($this);
}
}
class TestCopy extends Test
{
public $fakeAttribute;
}
function getTestCopy($object)
{
$copy = new TestCopy();
foreach($object->toArray() as $key => $value) {
if(method_exists($copy, 'set'.ucfirst($key))) {
$copy->{'set'.ucfirst($key)}($value);
}
}
return $copy;
}
$object = new Test();
$object->setId(1);
$object->setName('Tom');
$object->setAge(20);
$object->setNumber(10);
$copy = getTestCopy($object);
$copy->fakeAttribute = 'fake value';
echo "<pre>";
print_r($object->toArray());
print_r($copy->toArray());
output :
Array
(
[id] => 1
[name] => Tom
[age] => 20
[number] => 10
)
Array
(
[fakeAttribute] => fake value
[id] => 1
[name] => Tom
[age] => 20
[number] => 10
)

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

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