List all extended classes with their settings - php

I have a system where I am creating multiple classes that all extend from an abstract class.
Each class also declares 'settings' for that particular class type.
Example:
class First extends Base {
protected $name = 'First';
protected $lug = 'first';
protected $fields = [
'name',
'address',
'phone',
];
function __construct()
{
parent::__construct();
}
public function abstractMethod()
{
// do stuff for this particular class
}
}
and
class Second extends Base {
protected $name = 'Second';
protected $lug = 'second-one';
protected $fields = [
'first-name',
'last-name',
'email',
];
function __construct()
{
parent::__construct();
}
public function abstractMethod()
{
// do stuff for this particular class
}
}
Now what I want to be able to do is grab all extended classes and their 'settings' and return something like this:
$classes = [
'first' => [
'name' => 'First',
'slug' => 'first',
'fields' => ['name', 'address', 'phone']
],
'second' => [
'name' => 'Second',
'slug' => 'second-one',
'fields' => ['first-name', 'last-name', 'email']
]
];
So how would I go about doing this? Is there a better way?
I am using Laravel if that helps.
Edit: To Explain why not a duplicate
I'm not just after a way to get classes and their information I am after a way to architect this situation. I am essentially creating an extensible plugin system and need a way to Tell-Don't-Ask which plugins have been added.

I didn't try it, but it should work. Or it'll directs you.
$result = array();
foreach (get_declared_classes() as $class) {
if (is_subclass_of($class, 'Base'))
$result[] = get_class_vars($class);
}
But your properties needs to be public also.

What about using ReflectionClass? Getting properties is quite easy, example from manual below. Listing extended classes should be easy too.
<?php
class Bar {
protected $inheritedProperty = 'inheritedDefault';
}
class Foo extends Bar {
public $property = 'propertyDefault';
private $privateProperty = 'privatePropertyDefault';
public static $staticProperty = 'staticProperty';
public $defaultlessProperty;
}
$reflectionClass = new ReflectionClass('Foo');
var_dump($reflectionClass->getDefaultProperties());
Output:
array(5) {
["staticProperty"]=>
string(14) "staticProperty"
["property"]=>
string(15) "propertyDefault"
["privateProperty"]=>
string(22) "privatePropertyDefault"
["defaultlessProperty"]=>
NULL
["inheritedProperty"]=>
string(16) "inheritedDefault"
}

Using ReflectionObject you can do it like this:
$result = array();
foreach (get_declared_classes() as $class) {
if (is_subclass_of($class, 'Base')) {
$obj = new $class;
$refObj = new ReflectionObject($obj);
$props = $refObj->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);
$classProps = array();
foreach ($props as $prop) {
$property = $refObj->getProperty($prop->getName());
$property->setAccessible(true);
$classProps[$prop->getName()] = $property->getValue($obj);
}
$result[$class] = $classProps;
}
}
print_r($result);
Output:
Array (
[First] => Array (
[name] => First
[lug] => first
[fields] => Array (
[0] => name
[1] => address
[2] => phone
)
)
[Second] => Array (
[name] => Second
[lug] => second-one
[fields] => Array (
[0] => first-name
[1] => last-name
[2] => email
)
)
)

Related

Convert ZF2 Service Manager to ZF3

I have a simple ZF2 application that uses two tables and a service and I'm trying to convert it to run on ZF3. I can't work out how to update the service manager code. Here's an example of one of the controllers
<?php
namespace LibraryRest\Controller;
use Zend\Mvc\Controller;
use Library\Service\SpydusServiceInterface;
use Library\Service\SpydusService;
use Library\Model\BookTitle;
use Library\Model\BookTitleTable;
use Library\Model\Author;
use Library\Model\AuthorTable;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;
class SearchRestController extends AbstractRestfulController {
protected $bookTitleTable;
public function getBookTitleTable() {
if (! $this->bookTitleTable) {
$this->bookTitleTable = $this->getServiceLocator ()->get ( 'BookTitleTable' );
}
return $this->bookTitleTable;
}
protected $authorTable;
public function getAuthorTable() {
if (! $this->authorTable) {
$sm = $this->getServiceLocator ();
$this->authorTable = $sm->get ( 'AuthorTable' );
}
return $this->authorTable;
}
protected $spydusService;
public function __construct(SpydusServiceInterface $spydusService) {
$this->spydusService = $spydusService;
}
public function getList($action, $first, $last) {
if ($action == 'search') {
return $this->searchAction ( $first, $last );
}
}
public function searchAction() {
$message = array ();
$results = array ();
$first = urldecode ( $this->params ()->fromRoute ( 'first' ) );
$last = urldecode ( $this->params ()->fromRoute ( 'last' ) );
if ($this->getAuthorTable ()->getAuthorId ( $first, $last ) === false) {
$results [0] = array ('count' => 0, 'message' => 'This author not found in database', 'first' => $first, 'last' => $last, 'title' => '', 'titleCode' => '', 'link' => '', 'authorId' => '' );
} else {
$authorId = $this->getAuthorTable ()->getAuthorId ( $first, $last )->author_id;
$books = $this->spydusService->searchBooks ( $first, $last );
$count = count ( $books );
foreach ( $books as $foundTitle ) {
if ($foundTitle->getMessage () == 'Nothing found') {
$results [0] = array ('count' => 0, 'message' => 'Nothing found by library search', 'first' => $first, 'last' => $last, 'title' => '', 'titleCode' => '', 'link' => '', 'authorId' => '' );
break;
}
$searchBooks = $this->getBookTitleTable ()->getId ( $foundTitle->getTitle (), $authorId );
if ($searchBooks->count () == 0) {
$addUrl = "http://newlib.rvw.dyndns.org/library/search/add/" . $authorId . '/' . $foundTitle->getTitle ();
$results [] = array ('count' => $count, 'message' => $foundTitle->getMessage (), 'title' => $foundTitle->getTitle (), 'titleCoded' => $foundTitle->getTitleCoded (), 'first' => $foundTitle->getAuthorFirst (), 'last' => $foundTitle->getAuthorLast (), 'link' => $foundTitle->getLink (), 'authorId' => $authorId, 'addUrl' => $addUrl );
}
}
}
if (count ( $results ) == 0) {
$results [0] = array ('count' => 0, 'message' => 'Nothing found by library search', 'first' => $first, 'last' => $last, 'title' => '', 'titleCode' => '', 'link' => '', 'authorId' => '' );
}
return new JsonModel ( $results );
}
}
What code should I use instead of the getServiceLocator() call as this is no longer supported in ZF3? Elsewhere on Stack Overflow someone had replied to another question and suggested using a createService function but this has been dropped from ZF3 as well.
There are a couple of different approaches, but you're already using the most common one: passing the dependencies in through the constructor. You're currently doing this for your $spydusService class, so change the constructor to also accept arguments for the two table clases, something like:
class SearchRestController extends AbstractRestfulController
{
protected $bookTitleTable;
protected $authorTable;
protected $spydusService;
public function __construct(SpydusServiceInterface $spydusService, $bookTitleTable, $authorTable)
{
$this->spydusService = $spydusService;
$this->bookTitleTable = $bookTitleTable;
$this->authorTable = $authorTable;
}
[etc.]
}
then, somewhere you already have a factory for the SearchRestController (it might be a closure in your Module.php class, or a standalone factory class). You'll want to modify this to pass in the extra arguments:
public function getControllerConfig()
{
return array(
'factories' => array(
'SearchRestController' => function ($sm) {
$spydusService = $sm->get('SpydusService'); // this part you already have
$bookTitleTable = $sm->get('BookTitleTable');
$authorTable = $sm->get('AuthorTable');
return new SearchRestController($spydusService, $bookTitleTable, $authorTable);
}
)
);
}
You are going to want to create a factory to build controller. This new class will implement FactoryInterface. In the __invoke function, you'll use the $container instance to retrieve all of your dependencies of your controller and either pass them as arguments in the constructor or set them on the constructor instance. Then just return your controller instance from that function.
Your controller will need to be updated with fields to support this. You will also need to be sure to register your factory in your configuration.

Retrieving Data from an object of an array of arrays

I know this question is more data structures but since I am doing it in Symfony there might be a simpler way. I have a recursive function treeBuilder() I want to call on some data to create a hierarchy. Say a database of people and I want to create a tree structure if they live with their parents. I know I am passing an array of object to the function but it needs to be an array. I am pretty sure I need to rewrite this function so that it handles the the array of object but am stumped. I am not sure how to access the elements of the array to check the parentid. I know the code below is not correct but that is where I am at now.
Controller:
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('CompanyMyBundle:Org')->findAll();
var_dump($entities);
$tree=$this->treeBuilder($entities);
return array(
'entities' => $tree,
);
}
private function treeBuilder($ar, $pid=null)
{
$op=array();
foreach( $ar as $item ) {
// I know I have an array of objects
if( $item['ParentId'] == $pid ) {
$op[$item['Id']] = array(
'Street' => $item['Street'],
'ParentId' => $item['ParentId']
);
$children = self::treeBuilder( $ar, $item['Id'] );
if( $children ) {
$op[$item['Id']]['children'] = $children;
}
}
}
return $op;
}
var_dump($entities) from indexAction():
/export/www/working/symfony/src/Company/MyBundle/Controller/DepController.php:34:
array (size=60)
0 =>
object(Company\MyBundle\Entity\Org)[1556]
private 'Name' => string 'Me' (length=46)
private 'Street' => string '123 Sesame' (length=255)
private 'City' => string 'Myhometown' (length=255)
private 'ParentId' => int 0
private 'Id' => int 1
1 =>
object(Company\MyBundle\Entity\Org)[1557]
private 'Name' => string 'Me2' (length=46)
private 'Street' => string '123 Sesame' (length=255)
private 'City' => string 'Myhometown' (length=255)
private 'ParentId' => int 1
private 'Id' => int 2
If you need to get entities as arrays instead of objects, you would need to use Doctrine's hydrator:
$em = $this->getDoctrine()->getManager();
$orgRepo = $em->getRepository('CompanyMyBundle:Org');
$entities = $orgRepo->createQueryBuilder('org')
->getQuery()
->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
Note:
I would suggest to leave entities as objects and use getters:
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('CompanyMyBundle:Org')->findAll();
$tree = $this->treeBuilder($entities);
return array(
'entities' => $tree,
);
}
private function treeBuilder($entities, $pid = null)
{
$op = array();
/** Org $entity */ //Type hinting, if you use autocompletion
foreach ($entities as $entity) {
if ($entity->getParentId() == $pid) {
$op[$entity->getId()] = [
'Street' => $entity->getStreet(),
'ParentId' => $entity->getParentId()
];
$children = self::treeBuilder($entities, $entity->getId());
if (!empty($children)) {
$op[$entity->geId()]['children'] = $children;
}
}
}
return $op;
}

php - access class parent variable not using $this

class A {
protected $a = 'aaa';
}
class B extends A {
protected $a = 'bbb';
public function __construct(){
echo parent::$a; // Fatal error: Access to undeclared static property: A::$a in main.php on line 11
}
}
$b = new B();
I want to access $a variable from class A in constructor of class B. Be aware that $a variable is overwritten in class B. How can I access parent::$a?
The only way to do this would be to declare $a as static:
protected static $a = 'aaa';
But that will make the value of parent::$a the same for all instances. If you want separate values, this cannot be done, and you'd be better off renaming the variables, eg one is $a and the other is $b.
class A {
protected $a = 'aaa';
}
class B extends A {
protected $a = 'bbb';
public function __construct(){
echo parent::$a; // Fatal error: ...
}
}
$b = new B();
How can I access parent::$a?
You cant, parent::$a means you are trying to access a static property from a parent class.
instead of doing this,use the constructor to modify $a
class B extends A {
public function __construct(){
// do something with $this->a value here;
}
}
or you'll always overwrite $a if your redeclare it as a property in B.
I just read your comment so I understand your use case a little better now. If you are adding/merging configurations in inheriting classes I'd suggest an alternative approach, adding some behaviour.
As you confirmed above:
class A has a default configuration
class B can optionally pass in config values that can update/add to the default config
In this case, something like this could work for you:
class A
{
protected $config = array(
'foo' => 'foo',
'bar' => 'bar',
'baz' => 'baz',
);
public function __construct(array $config = array())
{
$this->config = array_merge($this->config, $config);
}
public function getConfig()
{
return $this->config;
}
}
class B extends A
{
// implement
}
$b = new B(array(
'foo' => 'OVERWRITTEN',
'new' => 'NEW',
));
print_r($b->getConfig());
Yields:
Array
(
[foo] => OVERWRITTEN
[bar] => bar
[baz] => baz
[new] => NEW
)
You can also overwrite your default config in the same way when using class A directly.
Alternatively, instead of implementing the merge in __construct() you could implement that as a setConfig() method.
Hope this helps :)
EDIT
I just want to add one more thing: if your config is a multidimensional array, you will have to change how you merge arrays. At first glance array_merge_recursive() might seem like the obvious candidate. However:
$old = array(
'foo' => 'foo',
'bar' => 'bar',
'baz' => array(
'baa' => 'baa',
'boo' => 'boo',
),
);
$new = array(
'foo' => 'FOO',
'baz' => array(
'baa' => 'BAA',
),
'new' => 'new'
);
$merge = array_merge_recursive($old, $new);
print_r($merge);
actually yields:
Array
(
[foo] => Array
(
[0] => foo
[1] => FOO
)
[bar] => bar
[baz] => Array
(
[baa] => Array
(
[0] => baa
[1] => BAA
)
[boo] => boo
)
[new] => new
)
Probably not what you are looking for! Instead use array_replace_recursive():
$merge = array_replace_recursive($old, $new);
print_r($merge);
This yields:
Array
(
[foo] => FOO
[bar] => bar
[baz] => Array
(
[baa] => BAA
[boo] => boo
)
[new] => new
)
#Darragh I made it little different because I didn't want to change my constructors:
abstract class A
{
protected $a = array('a' => 1, 'b' => 2);
public function __construct()
{
$this->mixA();
}
protected function a()
{
return array();
}
protected function mixA()
{
foreach ($this->a() as $key => $val) {
$this->a[$key] = $val; // $val can be an array too (in my case it is)
}
}
}
class B extends A
{
protected function a()
{
return array(
'b' => 'new value',
'c' => 'new variable'
);
}
public function dumpA()
{
var_dump($this->a);
}
}
$b = new B();
$b->dumpA();
So now if I want to change my default configs I just overwrite a() method. mixA() method can be expanded as needed.

How to give object a name

When I do the following:
$arUserStuff = array ('name' => 'username', 'email' => 'test#test.com');
$object = (object) $arUserStuff;
print_r($object);
The print function returns me the following:
stdClass Object ( [name] => username [email] => test#test.com )
How can I change std class object in let's say's User Object?
Create that class, then create an object of it:
class User {
public $name, $email; // public for this example, or set these by constructor
public function __construct( array $fields) {
foreach( $fields as $field => $value)
$this->$field = $value;
}
}
$object = new User;
$object->name = 'username';
$object->email = 'test#test.com';
Or, you can do:
$arUserStuff = array ('name' => 'username', 'email' => 'test#test.com');
$object = new User( $arUserStuff);
Now, from print_r( $object);, you'll get something like this:
User Object ( [name] => username [email] => test#test.com )
actually to do what you want, you should make it like:
$arUserStuff = new ArrayObject(
array (
'name' => 'username', 'email' => 'test#test.com'
)
);
to change the class name you need to create a new class.
It's a rather complex process but you can learn about it here:
http://php.net/manual/en/language.oop5.php
Here's a generic function that converts an array into any type of object, assuming the fields are public
class User { public $name, $email; }
class Dog { public $name, $breed; }
function objFromArray($className, $arr) {
$obj = new $className;
foreach(array_keys(get_class_vars($className)) as $key) {
if (array_key_exists($key, $arr)) {
$obj->$key = $arr[$key];
}
}
return $obj;
}
print_r(objFromArray('User',
array ('name' => 'username', 'email' => 'test#test.com')));
echo "<br/>";
print_r(objFromArray('Dog',
array ('name' => 'Bailey', 'breed' => 'Poodle')));
Output
User Object ( [name] => username [email] => test#test.com )
Dog Object ( [name] => Bailey [breed] => Poodle )
I wanted to make a trait out of it but don't have PHP 5.4 installed to test it. This wouldn't require the fields to be public
trait ConvertibleFromArray {
public static function fromArray($arr) {
var $cls = get_called_class();
var $obj = new $cls;
foreach($arr as $key=>$value) {
if (property_exists($obj, $arr)) {
$obj->$key = $value;
}
}
return $obj;
}
}
class User {
use ConvertibleFromArray;
public $name, $email;
}
class Dog {
use ConvertibleFromArray;
public $name, $breed;
}
print_r(User::fromArray(array ('name' => 'username', 'email' => 'test#test.com')));
print_r(Dog::fromArray(array('name' => 'Bailey', 'breed' => 'Poodle')));
?>

What is the right way to create nested classes in PHP?

I need to create a nested structure class of a multidimensional array, this is my array:
Array
(
[days] => Array
(
[0] => Array
(
[rows] => Array
(
[0] => Array
(
[activity_id] => 1
[name] => Activity 2
[city] => London
[info] => fsdsdshgsfd
)
[1] => Array
(
[activity_id] => 3
[name] => Activity 1
[city] => London
[info] => fsdhgsfd
)
)
)
[1] => Array
(
[rows] => Array
(
[0] => Array
(
[activity_id] => 3
[name] => Activity 1
[city] => London
[info] => fsdhgsfd
)
...
)
)
)
...
)
)
I have been trying to rewrite my code to make it class-driven, but I am struggling with that, what is the right way to build a class structure Itinerary->Days->Rows to replace an array? I tried something like this, I am not sure if it makes sense, I don't really understand the way how it has to be done:
class Itinerary
{
private $days = array();
public static function addDay($day) {
$this->$days[] = new ItineraryDay($day);
}
}
class ItineraryDay implements Countable
{
private $rows = array();
public static function addRow($row) {
$this->$rows[] = new ItineraryRow($row);
}
public function count()
{
return count($this->rows);
}
}
class ItineraryRow implements Countable
{
private $name;
private $city;
...
function __get($key)
{
...
}
function __set($key, $value)
{
...
}
public function count()
{
return count($this->rows);
}
}
$itinerary1 = new Itinerary();
$day1 = new ItineraryDay();
$itinerary1->addDay($day1);
$row1 = new ItineraryRow();
$day1->addRow($row1);
Can someone guide me?
It really depends what you ultimately want to do with said structure, but for a general idea I typically do something like this:
class Itinerary implements Countable
{
private $days;
public function __construct( array $days = array() )
{
$this->setDays( $days );
}
public function addDay( ItineraryDay $day )
{
$this->days[] = $day;
}
public function setDays( array $days )
{
$this->days = array();
foreach( $days as $day )
{
$this->addDay( $day );
}
}
public function count()
{
return count( $this->days );
}
}
class ItineraryDay implements Countable
{
private $rows;
public function __construct( array $rows = array() )
{
$this->setRows( $rows );
}
public function addRow( ItineraryRow $row )
{
$this->rows[] = $row;
}
public function setRows( array $rows )
{
$this->rows = array();
foreach( $rows as $row )
{
$this->addRow( $row );
}
}
public function count()
{
return count( $this->rows );
}
}
class ItineraryRow
{
private $id;
private $name;
private $city;
private $info;
public function __construct( $id, $name, $city, $info )
{
$this->id = $id;
$this->name = $name;
$this->city = $city;
$this->info = $info;
}
/* ... */
}
Then using it with the structure of your current array of data:
$days = array();
foreach( $originalData[ 'days' ] as $days )
{
$rows = array();
foreach( $days[ 'rows' ] as $row )
{
$rows[] = new ItineraryRow( $row[ 'activity_id' ], $row[ 'name' ], $row[ 'city' ], $row[ 'info' ] );
}
$days[] = new ItineraryDay( $rows );
}
$itinerary = new Itinerary( $days );
Or:
$itinerary = new Itinerary;
foreach( $originalData[ 'days' ] as $days )
{
$day = new ItineraryDay;
foreach( $days[ 'rows' ] as $row )
{
$row = new ItineraryRow( $row[ 'activity_id' ], $row[ 'name' ], $row[ 'city' ], $row[ 'info' ] )
$day->addRow( $row );
}
$itinerary->addDay( $day );
}
So, you can either pass "child" objects to the constructor (the method that constructs a new object), or add them with methods after construction. If you want the objects to be immutable, meaning you don't want to allow the objects to accept any more rows / days after construction, just make the addDay, setDays, addRow and setRows methods protected or private thereby only allowing passing "child" object through the constructors.
Be aware that, as PeeHaa already mentioned, you don't want static methods, because they operate class wide, not on individual instances of classes (objects). As a matter of fact, you cannot even use static methods the way you intended, because $this is only available in object context, not in class wide context.
But, to be honest, the question is a little bit to vague to be answered properly. We'd have to have a little more details about how you are going to construct the objects, and how you are going to use them later on.

Categories