Recently I came across interface from "Laravel 4 From Apprentice to Artisan" book with the example like this:
interface UserRepositoryInterface {
public function all();
}
class DbUserRepository implements UserRepositoryInterface {
public function all()
{
return User::all()->toArray();
}
}
What is interface? Where to put the interface file?
A Interface is a "contract" between itself and any class that implements the interface.
The contract states that any class that implements the interface should have all methods defined in the interface.
In this case DbUserRepository has to have a method named "all()" or a fatal error will occur when the class is instantiated.
The Interface file can be placed anywhere but the easiest is to put it in the same directory as the class that implements it.
The purpose of the interface is as follows:
Say you want to change your app from using a database (and Eloquent) and now instead you are going store data in JSON files and write your own methods for interacting with your JSON files. Now you can create a new repository e.g. JSONRepository and have it implement UserRepositoryInterface and because the interface forces you to define all the same methods that is defined in the interface, you can now be sure that your app will continue to work as it did. All this without you having to modify existing code.
The database example doesn't really make much real world sense to me because it is unlikely that I would change my storage system so drastically and the example always makes it seem like interfaces only have this one very small use case, which cant be further from the truth.
Coding to a interface has many benefits for you and your application.
Another example of interfaces in use can be:
Let's say you have a Calculator class and initially it has two operations it can perform (addition and multiplication). But a few weeks later you need to add another operation (e.g. subtraction), now normally this would mean you have to modify the calculator class and thus risk breaking it.
But if you are using a interface you can just create the Subtraction class and have it implement the CalculationInterface and now your app has a new operation without you touching existing code.
Example:
Calculator.php
<?php
class Calculator {
protected $result = null;
protected $numbers = [];
protected $calculation;
public function getResult()
{
return $this->result;
}
public function setNumbers()
{
$this->numbers = func_get_args();
}
public function setCalculation(CalculationInterface $calculation)
{
$this->calculation = $calculation;
}
public function calculate()
{
foreach ($this->numbers as $num)
{
$this->result = $this->calculation->run($num, $this->result);
}
return $this->result;
}
}
CalculationInterface.php
<?php
interface CalculationInterface {
public function run($num, $current);
}
Addition.php
<?php
class Addition implements CalculationInterface {
public function run($num, $current)
{
return $current + $num;
}
}
Multiplication.php
<?php
class Multiplication implements CalculationInterface {
public function run($num, $current)
{
/* if this is the first operation just return $num
so that we don't try to multiply $num with null */
if (is_null($current))
return $num;
return $current * $num;
}
}
Then to run the calculate method:
$this->calc = new Calculator;
$this->calc->setNumbers(5, 3, 7, 10);
$this->calc->setCalculation(new Addition);
$result = $this->calc->calculate(); //$result = 25
Now if you want to add a new operation let's say Subtraction you just create the Subtraction class and have it implement the CalculationInterface:
<?php
class Subtraction implements CalculationInterface {
public function run($num, $current)
{
/* if this is the first operation just return $num
so that we don't try to subtract from null */
if (is_null($current))
return $num;
return $current - $num;
}
}
Then to run it:
$this->calc = new Calculator;
$this->calc->setNumbers(30, 3, 7, 10);
$this->calc->setCalculation(new Subtraction);
$result = $this->calc->calculate(); //$result = 10
So in this example you are breaking your functionality up into smaller classes so that you can add, remove or even change them without breaking something else.
Related
I'm looking for more comfortable/more short version of Switch() statement in case of using multiple functions.
I'll give you one example: imagine 100-200 functions in one class, and you want to call only one of them by setting value to id in that class.
In my particular case, I have the following structure of PHP file:
<?php
class _main
{
function request($id)
{
switch($id)
{
case 0:
$this->writeA();
break;
case 1:
$this->writeB();
break;
///...
// then we have 100-200 functions like this in switch.
}
}
function writeA()
{
echo('a');
}
function writeB()
{
echo('b');
}
}
$id = 1;
$x = new _main();
$x->request($id);
?>
For some of you it may seem weird, but I don't want to have that much lines of code with case and break. For me, they are just making code more difficult to read.
(by the way, writing it 100 times will not making it fun for me too).
CONCLUSION
What could be the best,fast and comfortable method?
Can I store functions to array and then call them?
And will it affect performance? Will be Swicth() even faster?
Thank you :)
EDIT
Perhaps there is a different way of thinking/coding and not only array/switch thing.
I can't say I would ever recommend this but if you really want that many methods within a single class and a singular function to route the calls through...
<?php
class MyClass
{
public $id;
public function callFunction()
{
$funcName = 'execute' . $this->id;
return $this->$funcName();
}
private function execute1()
{
echo 'execute1() Called.';
}
private function execute2()
{
echo 'execute2() Called.';
}
}
$c = new MyClass();
$c->id = 1;
$c->callFunction();
Output:
execute1() Called.
I feel like there is most likely another way to approach this with more information utilising Interfaces and Abstract classes, but with the information to go off the above might suffice your requirement.
Edit: Sadly I don't have the time right now to come up with a detailed solution, and I don't really have enough information to go off but perhaps utilising interfaces is your best solution for your requirement. Below is a very quick example.
<?php
interface WritableInterface
{
public function write($data);
}
class VersionOneWriter implements WritableInterface
{
public function write($data)
{
return $data . '<br/>';
}
}
class VersionTwoWriter implements WritableInterface
{
public function write($data)
{
return $data . $data . '<br/>';
}
}
class MyMainClass
{
public function request(WritableInterface $writer, $data)
{
return $writer->write($data);
}
}
$c = new MyMainClass();
$w1 = new VersionOneWriter();
$w2 = new VersionTwoWriter();
echo $c->request($w1, 'DataString');
echo $c->request($w2, 'DataString');
Essentially when you call your request function you pass along a Writer class which implements the WritableInterface. Anything that implements that interface has to have a write() method.
Now when you pass your data across with your method, since you are also passing a writer along that can handle the data you can safely call ->write($data) within your request() method and the result will be dependent on the class you passed through.
If you ever need another method of writing you can just add create another class that implements your interface
Hopefully that made some sense, it was a bit of a ramble as I have to disappear for a bit. If you have any questions I'll try to check back when I have time.
--
Edit2:
The define() in this instance requires PHP7+ since I'm defining an array, but you could prior to PHP7 you could just use a standard array. $classMap = ['FirstClass', 'SecondClass'];
interface MyInterface {}
class FirstClass implements MyInterface {}
class SecondClass implements MyInterface {}
$requestParam = 1;
define('CLASS_MAP', array(
'FirstClass',
'SecondClass',
));
$classMap = CLASS_MAP[$requestParam]; // SecondClass
$class = new $classMap;
var_dump($class); // Dumps out: object(SecondClass)#1 (0) {}
I need help with some code desiging. I have a package which is used in many projects.
$p = new Package();
$result = $p->method();
While the Package looks like:
class Package {
public function method($fooArg = 1, $barArg = 1)
{
// some logic
return new SomeClass(
$fizzArg,
$buzzArg
);
}
}
Now, in one project which is using Package I need to change returned class. So, the call will look like this:
$p = new Package();
$result = $p->method(10, 10, true);
And the Package will look like this:
class Package {
public function method($fooArg = 1, $barArg = 1, $condArg = false)
{
// some logic
if (false === $condArg) {
return new SomeClass(
$fizzArg,
$buzzArg
);
}
return new MyNewClass(
$fizzArg,
$fooBarArg
);
}
}
Which design pattern should be used here? I do not want to return different object types based on condition, because it seems very ugly to me.
Since you explicitly set $condArg from the calling script and it is the only argument that control which instance to return, consider to create a second public method to return MyNewClass, and extract some logic into private method to share it between 2 public methods:
class Package {
public function method($fooArg = 1, $barArg = 1)
{
list $fizzArg, $fooBarArg = $this->someLogic($fooArg, $barArg);
return new SomeClass(
$fizzArg,
$buzzArg
);
}
public function newMethod($fooArg = 1, $barArg = 1)
{
list $fizzArg, $fooBarArg = $this->someLogic($fooArg, $barArg);
return new MyNewClass(
$fizzArg,
$fooBarArg
);
}
protected function someLogic($fooArg, $barArg)
{
// some logic
return [
$fizzArg,
$fooBarArg
]
}
}
This could be resolved with a combination of the Factory and Dependency Injection patterns:
The example below is a bit long winded, but it illustrates the basic principle. By providing your Package class with a factory implemented by the specific project. You don't need to change the code of that class. Instead, the changes are made with abstractions via interfaces.
/*
* Shared library
*/
interface IEntity
{
}
interface IFactory
{
/**
* #param $arg1
* #param $arg2
* #return IEntity
*/
public function create($arg1, $arg2);
}
class Package
{
protected $factory;
public function __construct(IFactory $factory)
{
$this->factory = $factory;
}
public function method($arg1, $arg2)
{
return new $this->factory->create($arg1, $arg2);
}
}
/*
* Project A
*/
class FactoryA implements IFactory
{
public function create($arg1, $arg2)
{
return new EntityA();
}
}
class EntityA implements IEntity
{
public function construct($arg1, $arg2)
{
}
}
/*
* Project B
*/
class FactoryB implements IFactory
{
public function create($arg1, $arg2)
{
return new EntityB();
}
}
class EntityB implements IEntity
{
public function construct($arg1, $arg2)
{
}
}
From a purely theoretical point of view, the very idea to use such a package that has to return something else based on where it is used is very ugly. This way it means that the widely-used package depends on a details of the package that uses it and this to me is a signal that you have to scrap the idea entirely and not use this package in this one project.
Your Package seems like a Factory method, it builds objects according to parameters. If I get it right, now you want to have different Packages for different projects with different objects.
Well Abstract factory is what you are looking for.
Make your Package abstract. Have two implementations, and load the proper package in the initiation phase you can use reflection or configuration or whatever PHP lets you do.
Note: It seems that there is some other logic in your Package class, if that logic is independent of building objects extract it to a different class, or vise versa.
since you don't have access to all project using Package, and you can change the source of Package if it does not affect other projects, then it is safer to create a descendant of Package instead. this way, you can change existing methods without affecting other projects, and you can also add new methods.
include('package.php');
class myPackage extends Package(){
public function newMethod($arg1, $arg2){
return new otherClass($arg1, $arg2);
}
//if you want to change existing method
public function method($fooArg = 1, $barArg = 1){
//some new logic
}
}
then you can use it in your project:
$obj = new myPackage();
if ($i_want_regular_class){
$newObj = $obj->method(1, 2); // call parent's method or modified parent's method
} else {
$newObj = $obj->newMethod(3, 4); // call new method
}
as for why i suggest you to create new method is because you already know which object you want to create, hence the argument passed to the method. so instead of putting the conditional in the method, why not put the conditional in the logic and call the appropriate method?
So I have read that if we see a switch statement, its a sign that it needs polymorphism.
I saw such polymorphism example:
include 'vendor/autoload.php';
$calc = new Calculator();
$calc->setOperands(5, 6);
$calc->setOperation(new Addition);
echo $result = $calc->calculate();
And of course there can be various classes as Subtract, Multiply, Root, etc.
Now lets say I want to use this code in a Laravel framework, but this I think should apply to any php framework.
Example of addition class ( same way could work any other calculator function)
Class Addition implements Operation {
public function run($num, $current){
return $current + $num;
}
}
Calculator:
Class Calculator {
protected $result = 0;
protected $operands = array();
protected $operation;
public function getResult()
{
return $this->result;
}
public function setOperands()
{
$this->operands = func_get_args();
}
public function setOperation(Operation $operation)
{
$this->operation = $operation;
}
public function calculate()
{
foreach ($this->operands as $num) {
echo $num;
if ( ! is_numeric($num)) {
throw new InvalidArgumentException;
}
$this->result = $this->operation->run($num, $this->result);
}
return $this->result;
}
}
I write a class like this:
class CalcUser
{
private $calc;
public function __construct(Calculator $calc)
{
$this->calc = $calc;
}
public function index()
{
$this->calc->setOperands(5, 6);
$this->calc->setOperation(new Addition);
$result = $calc->calculate();
// imagine we have long formula to calculate so we add here many functions
// (5+6) * 12 + 21 / 6 + sqrt(4) ...
$this->calc->setOperands($result, 6);
$this->calc->setOperation(new AnyOtherFunction);
echo $result = $calc->calculate();
}
}
And this should work, did not test my CalcUser class, just wrote directly here.
But I see one problem - there is used keyword new
And also what I have read is this:
Signs of Untestable Code:
New Operators
The only time when it’s acceptable to instantiate a class inside of
another class is when that object is what we refer to as a
value-object, or a simple container with getters and setters that
doesn’t do any real work.
Ok, now I could add the Addition class, and other classes to constructor as parameter like I did with calculator class and new operator will be avoided.
But then there is another thing:
Too Many Dependencies
If you find that a particular class requires four or more
dependencies, this is, more often than not, a tell-tale sign that your
class is asking for too much
And so its easily to get more than 3 dependencies that way with calculator alone having many different functions.
So how should I reformat code to avoid having too many dependencies?
There are a bunch of different views on this matter (when does a class depend on something), but class dependencies are typically seen as what's passed into the constructor, i.e. what's needed for the class to be instantiated as an object. Therefore, when you have an instance of your calculator, calling a method and passing another object - in this case an implementation of Operation - into a method is not a direct dependency.
So basically your Calculator class has no dependencies, your CalcUser has one dependency (Calculator).
Also, I think the thing about the new-keyword/construct is that a class should not call something on itself, passing a method dependency through there. That could be a sign that the newly instantiated object is redundant if it's only used in that class' ecosystem. Say you never use Operation anywhere else beside in the class that depends on it, i.e. in this case:
class Calculator
{
...
public function newSumOperation()
{
$this->setOperands(func_get_args());
$this->setOperation(new Addition);
}
...
}
class CalcUser
{
...
public function index()
{
$this->calc->newSumOperation(1,2,3);
$result = $this->calc->calculate();
// imagine we have long formula to calculate so we add here many functions
// (5+6) * 12 + 21 / 6 + sqrt(4) ...
$this->newXXXXXOperation(4,3,2);
echo $result = $calc->calculate();
}
}
So, as you see, in the above example you never use Addition outside the Calculator-class. If you think of a real calculator, you put numbers in and get the result out; and in between that, the calculator doesn't push the logic of adding numbers together over to something else, because it's the calculators job to do an addition.
I'm wondering if anyone could give me a suggestion for to best handle this situation:
I have several systems from which to pull data to display on a single PHP-driven website. The type of information will be the same across systems (contacts, addresses, etc) but the way I pull data (MS-SQL, XML, REST) will not.
I want to create a class, or set of classes, for each of the connection types and use simple methods such as getContact(), getAddress(), etc. I am wondering how best to structure this.
The most obvious way that comes to mind means creating classes for each connection type, like:
class.sys_mysql.php. class.sys_xml.php, etc
But then won't I be duplicating the methods in each class? Maybe that's OK, but I'm curious if there's a better way, as far as future maintenance goes.
Maybe I should simply isolate the queries/data extraction methods, into separate class files? Classes within classes? Extended classes? I'm less familiar with these.
Any advice would be greatly appreciated.
DC
--------- more info ----------
Hi all. I really appreciate all the great advice. Not to belabor this thread but I'm still a bit confused on how I should break things down. I will try and be a bit more specific:
Basically, I have 3 (more in the future) offices, from which one PHP website pulls information. Each office uses a different CRM, and a different system for interfacing with that CRM. One uses MSSQL, another XML requests, etc.
Each office wants to display information similarly on the website, but there are minor differences. There may be more differences in the future. However, there are by far more similarities, and so I want to capitalize on higher level functions like getContacts($id) which are shared between them.
I am trying to write these classes so I can:
1) use higher level methods to pull data easily
2) account for different ways of pulling data (xml,sql,etc)
3) account for differences between how data is displayed on the website (office 1, office 2, office 3)
4) manage the connection credentials for each office and allow for expandability_
5) I should also mention that I will be creating separate classes for reporting, sending out automated e-mails, calculating finances...separate modules that will need to use existing classes to pull data.
I realize that some of the examples here see to cover 1 and 2, but I am confused as to how to get 3, 4 and 5 working with 1 and 2.
I really appreciate the help.
DC
This is what Interfaces are for.
You define the methods required to interact with the data in an Interface, and then you create classes that implement that Interface
If some of the systems have similar access models (i.e. perhaps two different DB Servers, but both are accessed using PDO) you could abstract it further and put the "low level" functionality into service-specific classes (which implement an Interface) and then a higher-level class which defines the actual methods you use.
Another option is that you could put the "common" methods (those that are identical or can be made idetntical with service-type checks) into a base class, which all others extend.
Example for option one:
interface DataModel {
public function findContacts($search);
public function getContact($id);
public function findAddresses($search);
public function getAddress($id);
}
class XMLDataModel implements DataModel {
public function findContacts($search) {
...
}
public function getContact($id) {
...
}
public function findAddresses($search) {
...
}
public function getAddress($id) {
...
}
}
class RESTDataModel implements DataModel {
public function findContacts($search) {
...
}
public function getContact($id) {
...
}
public function findAddresses($search) {
...
}
public function getAddress($id) {
...
}
}
As you can see, you simply define an Interface, which specifies which methods a class must implement.
If you had two very similar classes, perhaps one for MySQL and one for PostreSQL, and you can't/don't want to combine them into a single PDO class, you could do the following:
class PDODataModel implements DataModel {
private $model;
public function __construct ($serverType) {
if ($serverType === 'mysql') {
$this->model = new MySQLPDODataModel();
}
elseif ($serverType === 'postgresql') {
$this->model = new PostgresQLPDODataModel();
}
}
public function findContacts($search) {
// common logic about $search, perhaps checking it's a valid search?
$result = $this->model->searchForContacts($search);
// more common logic, maybe higher level filtering..
return $result;
}
public function getContact($id) {
...
}
public function findAddresses($search) {
...
}
public function getAddress($id) {
...
}
}
interface PDODataModelDriver {
public function searchForContacts($search);
}
class MySQLPDODataModel extends PDODataModel implements PDODataModelDriver {
public function searchForContacts($search) {
// MySQL-specific query to search for contacts
}
}
class PostgresSQLPDODataModel extends PDODataModel implements PDODataModelDriver {
public function searchForContacts($search) {
// PostgreSQL-specific query to search for contacts
}
}
The other option I mentioned was to work in the opposite direction:
abstract class PDODataModel implements DataModel {
protected $pdo;
protected $dsn;
public function __construct () {
$this->pdo = new PDO($this->dsn);
}
public function findContacts($search) {
// common logic about $search, perhaps checking it's a valid search?
$result = $this->searchForContacts($search);
// more common logic, maybe higher level filtering..
return $result;
}
public function getContact($id) {
...
}
public function findAddresses($search) {
...
}
public function getAddress($id) {
...
}
}
class MySQLPDODataModel extends PDODataModel {
protected $dsn = 'mysql:dbname=testdb;host=127.0.0.1';
protected function searchForContacts($search) {
// MySQL-specific query to search for contacts
}
}
class PostgresSQLPDODataModel extends PDODataModel {
protected $dsn = 'pgsql:host=localhost;port=5432;dbname=testdb';
protected function searchForContacts($search) {
// PostgreSQL-specific query to search for contacts
}
}
This is a classical example of a strategy design patter. Your first mind was absolutely fine, but if you're repeating yourself in each class you should consider creation of a abstract class that will handle the common code.
So it could look like this:
$myService = new MyService(new XMLReader('/path/to/file'));
echo $myService->getContanct('abc')->getName();
And skeleton of your classes:
class MyService {
private $reader;
public function __construct(ReaderInterface $reader) {
$this->reader = $reader;
}
// ...
public function getContacnt($id) {
$contact = $this->reader->getContact($id);
// do some extra stuff here
return $contact;
}
}
interface ReaderInterface {
public function getContanct($id);
public function getAddress($id);
}
abstract class AbstractReader implements ReaderInterface {
protected $loaded = false;
protected $data = array();
abstract protected function load();
public function getContanct($id) {
if ($this->loaded == false) {
$this->load();
$this->loaded = true;
}
return $this->data['contact'][$id];
}
}
class XMLReader extends AbstractReader {
public function __construct($filepath) {
...
}
protected function load() {
...
foreach (...) {
$this->data[...] = ...;
}
}
}
class MSSQLReader extends AbstractReader {
public function __construct(PDO $dbh) {
...
}
protected function load() {
...
while ($row = $stmt->fetchRow()) {
$this->data[...] = ...;
}
}
}
EDIT (2011-03-07) - According to your comment.
PHP supports variable variables (new $type()) but never use this! It's a horrible, and if overused make code really crappy.
This is a yet another example of a "classical issue". Use a factory pattern (depending on the complexion of the creation you might want to use more abstract variety of this pattern - abstract factory
When you need to dynamically determine class name (eg. from variable) use reflection API to instate an object.
You should create an object-storage mapping layer for each data source, which instantiates the objects into storage agnostic model objects. See http://martinfowler.com/eaaCatalog/dataMapper.html
If you have control over the structure of your data formats, I suggest you serialize your data in a consistent way (especially in XML) and provide drivers for each data format.
For instance, every driver will have 'findAll', 'getOne', 'count', etc. methods. The driver can be given a model to populate with the retrieved data.
abstract class DataDriver {
function __construct($model) {}
abstract public function findAll();
abstract public function getOne();
abstract public function count();
// ...
}
class XMLDriver extends DataDriver {
// implements all the methods
}
class SQLDriver extends DataDriver {
// implements all the methods
}
class Contact {
public var $firstName;
public var $lastName;
function getFullName() {
return trim($this->firstName . ' ' . $this->lastName);
}
}
$accessor = new SQLDriver('Contact');
$contacts = $accessor->findAll();
If your data will be serialized in an uncontrolled manner, the approach you suggest is the best. Just make sure to separate your models (e.g. Address book, Contact) from the method of retrieval (eg. get_address_book_xml, get_address_book_sql, etc.)
Of course there are many ways of separating your models from your data-mapping driver. The importance is you find the solution that works best for you given that you're using such different formats.
I have a PHP MVC application using Zend Framework. As presented in the quickstart, I use 3 layers for the model part :
Model (business logic)
Data mapper
Table data gateway (or data access object, i.e. one class per SQL table)
The model is UML designed and totally independent of the DB.
My problem is : I can't have multiple instances of the same "instance/record".
For example : if I get, for example, the user "Chuck Norris" with id=5, this will create a new model instance wich members will be filled by the data mapper (the data mapper query the table data gateway that query the DB). Then, if I change the name to "Duck Norras", don't save it in DB right away, and re-load the same user in another variable, I have "synchronisation" problems... (different instances for the same "record")
Right now, I use the Multiton / Identity Map pattern : like Singleton, but multiple instances indexed by a key (wich is the user ID in our example). But this is complicating my developpement a lot, and my testings too.
How to do it right ?
Identity Map
Edit
In response to this comment:
If I have a "select * from X", how can I skip getting the already loaded records ?
You can't in the query itself, but you can in the logic that loads the rows into entity objects. In pseudo-code:
class Person {}
class PersonMapper {
protected $identity_map = array();
function load($row) {
if (!isset($this->identity_map[$row['id']])) {
$person = new Person();
foreach ($row as $key => $value) {
$person->$key = $value;
}
$this->identity_map[$row['id']] = $person;
}
return $this->identity_map[$row['id']];
}
}
class MappingIterator {
function __construct($resultset, $mapper) {
$this->resultset = $resultset;
$this->mapper = $mapper;
}
function next() {
$row = next($this->resultset);
if ($row) {
return $this->mapper->load($row);
}
}
}
In practice, you'd probably want your MappingIterator to implement Iterator, but I skipped it for brevity.
Keep all loaded model instances in "live model pool". When you load/query a model, first check if it has been already loaded into pool (use primary key or similar concept). If so, return the object (or a reference) from pool. This way all your references point to the same object. My terminology may be incorrect but hopefully you get the idea. Basically the pool acts as a cache between business logic and database.
Multiton
Best option if you want to use a variety of singletons in your project.
<?php
abstract class FactoryAbstract {
protected static $instances = array();
public static function getInstance() {
$className = static::getClassName();
if (!(self::$instances[$className] instanceof $className)) {
self::$instances[$className] = new $className();
}
return self::$instances[$className];
}
public static function removeInstance() {
$className = static::getClassName();
if (array_key_exists($className, self::$instances)) {
unset(self::$instances[$className]);
}
}
final protected static function getClassName() {
return get_called_class();
}
protected function __construct() { }
final protected function __clone() { }
}
abstract class Factory extends FactoryAbstract {
final public static function getInstance() {
return parent::getInstance();
}
final public static function removeInstance() {
parent::removeInstance();
}
}
// using:
class FirstProduct extends Factory {
public $a = [];
}
class SecondProduct extends FirstProduct {
}
FirstProduct::getInstance()->a[] = 1;
SecondProduct::getInstance()->a[] = 2;
FirstProduct::getInstance()->a[] = 3;
SecondProduct::getInstance()->a[] = 4;
print_r(FirstProduct::getInstance()->a);
// array(1, 3)
print_r(SecondProduct::getInstance()->a);
// array(2, 4)