PHP inheriting or compositing from multiple storage interfaces/objects - php

I have a situation where I need to abstract with storage functions, and to have multiple database adapters.
However I'm relying on external vendors who also have multiple database adapters for their libraries.
I'd like to create a single adapter be it MySQL that inherits the functions of the corresponding MySQL adapters from the external vendors. I can dependency inject this adapter into my own libraries and the external libraries that depend upon adapters to function.
Of course PHP doesn't have multiple inheritance, so I did some research and came up on composition.
Would compositing multiple database adapters into a single database adapter be a good practice? Furthermore would this composed object work, if it implemented an interface that extends from the corresponding interfaces of the external vendors?
For example imagine having:
External1\StorageInterface
External1\MySQLAdapter
External2\StorageInterface
External2\MySQLAdapter
Internal\StorageInterface
Internal\MySQLAdapter
Now: Internal\StorageInterface extends External1\StorageInterface, External2\StorageInterface
Then: Internal\MySQLAdapter implements Internal\StorageInterface
Then: Internal\MySQLAdapter compositions External1\MySQLAdapter and External2\MySQLAdapter
On a side note, how should the compositing take place? Via __call or reimplementing the function names, and simply calling the child objects? Which one satisfies the interface constraints?
One more question would be, how does one deal if in the case that different adapters have the same function name creating conflict? Would the adapter pattern work?

Related

Laravel reusable functions

I am using Repository design pattern and I have a function generateBarcode() this function just do some logic and insert data in database.
I am calling this function in more one function and more that one repository to generate a new Barcode.
Question is:
What is the best way to make this function reusable?
Helpers
But I don't think this is a good idea since it am dealing with database.
Events
Firing event and storing the result.
$barcode = event(new NewBarcodeRequired())
That what I am doing right now and data is returned as an array
Also I don't think that is a good idea because I have read that events shouldn't return data.
Repository
Create a new repository for this function but I think it is a very bad idea because I won't create a class for every reusable function that I have.
Traits could be a good option for this case. Which will give you flexibility to use in any of your class without requirement of class extension.
Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.
A Trait is similar to a class, but only intended to group
functionality in a fine-grained and consistent way. It is not possible
to instantiate a Trait on its own. It is an addition to traditional
inheritance and enables horizontal composition of behavior; that is,
the application of class members without requiring inheritance.
http://php.net/manual/en/language.oop5.traits.php

Is a repository or service provider required?

I am building a Laravel 5.3 app that pulls data from a number of potential sources. It's a fallback system with 3 sources:
Database
If not found, source 1
If not found, source 2
All 3 sources are quite simple and will be accessed in the same way, by using the following 2 methods:
function get($id)
function query($type, $string)
I'm aware there is various terminology around the different ways to implement this, but I'm unsure after reading the docs what the cleanest approach is. Should each data source be implemented as a Repository? A ServiceProvider wrapped in a container? I find the docs thorough but also lacking in overall/high level explanations, so any pointers are appreciated.
The Repository Pattern is the following:
Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects. Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.
With that in mind, you can say that Eloquent itself is a much larger implementation of the Repository Pattern, but a Repository nonetheless. Since it's an ActiveRecord implementation, there isn't any real separation between the Repository and Storage mechanisms.
On to your question specifically, Laravel won't really cover the Repository Pattern itself in much the same way it doesn't cover Service classes or Singletons: It's not Laravel's responsibility to teach you these patterns, it's just giving you the means to organize these patterns more easily if you choose to implement them.
All that said, I would agree with you that each data source implement its own RepositoryInterface. From there, you can register your own ServiceProvider that in turn instantiates a custom Service Class whose purpose is to return the appropriate Repository.
If determining the appropriate Repository is light in logic, and is dependent only on the Controller responsible for the alternate data source, you can likely use Contextual Binding and skip the Service Class altogether.
Either way, there's a few ways to skin this cat, but you're on the right track.
Edit: As an aside, if you want to strictly go "by the book" on this, you would probably want to separate out different Storage classes that connect to each data store separately, which you can then query as appropriate. Then your Repository - which is likely housing the same type of data collection regardless of its storage origins - can be responsible for the returned results.
Otherwise, if you want to stick with Eloquent as much as possible, you can look into multiple data connections to house each of your data sets.

What are the differences between Joomla Model Types?

I'm trying to get to grips with the power behind Joomla (3.x)'s framework.
I've noticed that there are multiple types of model that can be used in a component:
JModelAdmin
Prototype admin model. Acts as a Factory class for application specific objects and provides many supporting API functions.
JModelLegacy
Base class for a Joomla Model
Acts as a Factory class for application specific objects and provides many supporting API functions.
JModelList
Model class for handling lists of items.
Acts as a Factory class for application specific objects and provides many supporting API functions.
JModelForm
Prototype form model.
Acts as a Factory class for application specific objects and provides many supporting API functions.
JModelItem
Prototype item model.
I understand that JModelLegacy seems to be the foundation class. My models have been extending JModelLegacy by default, however, I was wondering if I could be potentially using the benefits from the other classes.
If there was someone who knows about these models, I would appreciate having an explanation about what the differences are between these model classes, and an intended scenario where you would use one over others.
First of all all the classes are available for code study under:
\libraries\legacy\model\
It's also important to understand that these classes should be used (generally speaking) in connection with the corresponding controllers: JControllerLegacy, JControllerForm and JControllerAdmin.
JModelLegacy - is the base class for the Joomla model (model as in MVC). It will basically work as a Factory class by initializing the database driver object and the table object.
You may want to extend this class if you just want to do some basic SQL queries (any work with JDatabase) and write other business logic.
All models will extend JModelLegacy.
JModelList - is a class for handling lists of items. It provides pagination and filtering. Basically everywhere you display a list of items, you can use JModelList. All core components rely on JModelList.
JModelForm and JModelAdmin are generally associated with forms. Forms can be the the User registration form or creating and editing a record. Forms in Joomla are defined in XML files. JModelForm will load this files as JForm objects, will load form data, preprocess the form and validate it.
This is one of the most powerful classes that you can use. They will do the heavy lifting. When you don't like a specific behaviour you can override it by implementing your own code.
JModelAdmin adds some extra admin functionalities to the form:
perform batch operations on records.
will do ACL checks on records.
JModelAdmin will generally be used when editing a record or for batch operations, especially in backend.
JModelItem - very unlikely you will need it. It exposes just a method getStoreId() and two properties. You won't need this class, unless for as a naming thing, instead of using JModelLegacy you want to extend it when doing something basic, such as displaying a record. (my personal understanding of things).
Conclusion: Above is a general introduction to this classes, as I see them. My suggestion is to look into detail how Joomla uses them, what methods are exposed and how to use them. They are very powerful classes, and especially for CRUD operations they will help you do all the heavy lifting. After you understand what they do, you can use them and override them when needed.

repository pattern vs ORM

What good is a repository pattern when you have an ORM?
Example. Suppose i have the following (fictional) tables:
Table: users
pk_user_id
fk_userrole_id
username
Table: userroles
fk_userrole_id
role
Now with an orm i could simply put this in a model file:
$user = ORM::load('users', $id);
Now $user is already my object, which could easily be lazy loaded:
(would be even nicer if things are automatically singular/pluralized)
foreach ( $user->userroles()->role as $role )
{
echo $role;
}
Now with the Repository pattern i'd had to create a repository for the Users and one for the Roles. The repository also needs all kinds of functions to retrieve data for me and to store it. Plus it needs to work with Entity models. So i have to create all of those too.
To me that looks like alot of stuff do... When i could simply get the data like i described above with an ORM. And i could store it just as easy:
ORM::store($user);
In this case it would not only store the user object to the database, but also any changes i made to the 'Roles' object aswell. So no need for any extra work like you need with the repository pattern...
So my question basically is, why would i want to use a repository pattern with an ORM? I've seen tutorials where to use that pattern (like with Doctrine). But it really just doesn't make any sense to me... Anyone any explanation for its use in combination with an ORM..??
The ORM is an implementation detail of the Repository. The ORM just makes it easy to access the db tables in an OOP friendly way. That's it.
The repository abstract persistence access, whatever storage it is. That is its purpose. The fact that you're using a db or xml files or an ORM doesn't matter. The Repository allows the rest of the application to ignore persistence details. This way, you can easily test the app via mocking or stubbing and you can change storages if it's needed. Today you might use MySql, tomorrow you'll want to use NoSql or Cloud Storage. Do that with an ORM!
Repositories deal with Domain/Business objects (from the app point of view), an ORM handles db objects. A business objects IS NOT a db object, first has behaviour, the second is a glorified DTO, it only holds data.
Edit
You might say that both repository and ORM abstract access to data, however the devil is in the details. The repository abstract the access to all storage concerns, while the ORM abstract access to a specific RDBMS
In a nutshell, Repository and ORM's have DIFFERENT purposes and as I've said above, the ORM is always an implementation detail of the repo.
You can also check this post about more details about the repository pattern.
ORM and repository pattern...depends on setup.
If you use your ORM entities as the domain layer, then please use no repositories.
If you have a separate domain model and you need to map from that model to ORM entities and so perform a save, then repositories are what you need.
More details you find here (but must be logged to linked-in). Also to understand the difference, check out the definition of the repository pattern.
Most people use classes that they call repositories, but aren't repositories at all, just query classes - this is how/where you should place your queries if you decided to go with the #1 option (see answer above). In this case make sure not to expose DbContext or ISession from that query class, nor to expose CUD-methods from there - remember, Query class!
The #2 option is a tough one. If you do a real repository, all the inputs and outputs on the repository interface will contain clear domain classes (and no database related object). It's forbidden to expose ORM mapped classes or ORM architecture related objects from there. There will be a Save method also. These repositories might also contain queries, but unlike query classes, these repos will do more - they will take your domain aggregate (collection and tree of entities) and save them to DB by mapping those classes to ORM classes and perform a save on ORM. This style (#2) does not needs to use ORM, the repository pattern was primarly made for ADO.NET (any kind of data access).
Anyhow these 2 options are the 2 extremes we can do. A lot of people use repositories with ORM, but they just add an extra layer of code without real function, the only real function there is the query class like behaviour.
Also I'd be careful when someone talks about UnitOfWork, especially with ORM. Almost every sample on the internet is a fail in terms of architecture. If you need UoW, why not use TransactionScope (just make sure you got a wrapper which uses other than Serializable transaction by default). In 99,9% you won't need to manage 2 sets of independent changes in data (so 2 sets of OuW), so TransactionScope will be a fine choce in .NET - for PHP i'd look for some open-session-view implementations...

What design pattern would apply when I need to retrieve data from both MySQL DB and local XML files?

I am currently using Doctrine 2 to handle the ORM with the mysql db, but if I also wanted to store the same data in an XML format, and be able to retrieve from both data sources, what would be the best way to do this? Thanks in advance for your time.
The Abstract Factory pattern
Define an Interface that includes all the operations you need to perform.
Create two concrete classes that both implement that interface, but implement the interface methods differently.
Create a factory method with a signature of returning the interface you defined, and can return instances of either concrete type based on a parameter.
Program to the only to the interface (and not the concrete classes).

Categories