How to pass user data to service from controller using PHP-DI - php

My controllers have an account object and a user object, and almost all interactions with the backend depends on these objects to set access rights, limit data loads, ++++ (I am not using any specific framework)
My controllers have different ways of knowing which objects to use, but usually this is in the session for logged in users (but backend processes might get this information from the queue etc).
So, I am trying to setup PHP-DI for my ServiceLayer and I need to inject Account, User object to the services, but how do I do this in a good way ensuring that these have the right values?
My first attempt was to pass this into a ContainerFactory:
public static function getInstance(EnvironmentConfig $config, ?int $accountId, ?int $userId):Container
Then use these values dynamically in the configuration, however this stopped working when I enabled compilation as the values got cached. (obvious but yes..)
I can use a factory for creating the userObject and Account object and e.g read the values directly from the session in the Factory. But this feels very dirty, and will only work in certain contexts.
The documentation only deals with environment specific values, so I have not found any good description with how to deal with session specific data.
Any suggested patterns for this?

A container should store stateless objects. Request-specific data like session, logged in user, etc. are not dependencies, trying to put them into the container means going back to global state.
I highly recommend you pass that data through other ways: method call parameters, store them inside a Request object, at worse inject a RequestStack or similar object. That's what Symfony did when they deprecated injecting the Request objects directly using the container: https://symfony.com/blog/new-in-symfony-2-4-the-request-stack

Thanks for your quick reply. Principally I do agree, these things are border line as they are intrinsic to all application layer, the application has a global state depending on logged in account and user and that remains like that for the entire session. Yes this is technically request specific, but I need the service layer to be aware of this as so much business logic depends on it.
method call parameters would be technically clean, but super-messy and error prone as this would be the same parameters repeated all over in the application. All the service calls would end up like this:
$service->getCategory($id, $user, $account);
$service->getCategoryByMain($mainCategoryId, $user, $account);
Hence I was looking at PHP-DI to get a cleaner injection than my current setup where I get long Service constructors that are the same all over in the application.
Not sure how to make this neat, so open for any good practical suggestions :) Maybe PHP-DI is not the right tool here, but this is DI problem, where I have a set dependencies that needs to be pushed down in the stack.

Related

Drivers vs Controllers (MVC)

I am working with Codeignitor 2.x and I was originally using controllers as modules (though not completely HMVC), in that I had a Top Level controller that would call other lower level controllers. My thinking was that because these lower level controllers were still interacting with the view, that they should remain controllers rather than models or drivers.
What I found, however, is that each instance of a controller also spawns a new instance of CI. So I would have 3 or 4 instances of CI running for each request. Ton of overhead, and also caused session issues.
I have since moved these lower level controllers into the library as drivers. They now capture the CI instance in the construct method, and make modifications to it. This makes it VERY nice to work with, and doesn't require the HMVC extension. The drivers are not externally callable either, so it allows me to funnel all requests through specific entry points.
My question is whether this is structurally correct. I have always held the notion that drivers should only modify the data they are provided through their method calls, but many of these drivers will pull information directly from GET and POST, and while they will not directly append to the View, they are often accessing view files, and passing the processed view to the CI instance for output.
[EDIT] A little more context:
One of the drivers I have created is essentially a user login driver called 'Access'. It makes calls to the 'User' model for create/login/logout methods. The driver uses the POST data to check the User model, then loads the correct view with errors and whatever is needed. The idea, being, with 2 lines, I can include this driver in any controller throughout the project, so there is a significant decrease in code redundancy. Again, I know that the drivers should be confined to their scope, however the driver does not modify anything outside it's scope, but simply returns the view it has created.
Is there another method to for doing this that is more inline with straight MVC?
I can't say whether it is right or wrong. But if I were you, I wouldn't do that. I'd probably refactor some of the code. I'd make sure that they don't grab and manipulate data directly from the $_GET or $_POST superglobals. Instead, pass in some data as arguments to a function call. This would make testing easier, since you don't have to simulate a GET or a POST request. While technically, you could just set the value for the superglobals manually from the code, but I'd not recommend doing that. Supplying data as arguments would be much better, especially if you want to write test cases that are to be executed subsequently. Plus, having the libraries interacting with the scopes beyond its own might introduce some hidden gotchas.
In my opinion, libraries are meant to be something like modules, where you can just drag and drop, and then use them without any hassle. If your code really needs to grab or manipulate values from $_GET or $_POST, maybe they are meant to be models instead. Also, you might want to think whether your code is actually a library or not. Ask yourself, will this code be useful outside this application? Or is it highly dependent and can only be useful for this particular app? If you say yes to the latter, then it's probably should be a model instead of a library. Last thing, you should leave the views to the controller. Just return the data you need from the library/model method then pass it to the view from the controller.

Should you handle session data in a controller or a model for an MVC framework?

I am working with an MVC framework (specifically, PHP's CodeIgniter). I am trying to follow "best practices" as much as possible, but I don't have much experience with MVC. Is it bad practice for me to retrieve data from a session within the Controller? Should I "ask" the model if, say, a particular session value is 'foo' or 'bar', or should I do that directly inside the Controller? I'm thinking I should do it inside the Model since the session data is technically data, but I just want to make sure. To be clear, I don't store the session data in the database at all, so I'm not running a query.
Models typically handle all domain objects that are persisted to some sort of long-term storage. They may or may not have transient values in them that have to do with the particular application's use of them.
Controllers should be querying any data they need in order to correctly route and display information. It may help to create a 'Service' layer that operates directly on domain objects (your model) and provides an API for Controllers to use. The main thing to not include in Controllers is business logic.
It would be reasonable, for instance, for the Controller to grab the referring page and do something with that data in regards to the user flow. However, apart from validation, it probably shouldn't, say, examine the amount of money being transferred between accounts - it should just pass that on to a service object that instantiates and works with the correct domain objects.
Questions to ask about logic you're putting into a Controller:
Does this logic help figure out what Model objects I need? If not, it shouldn't be here.
Does this logic help figure out what View objects will be used to construct the response to the user? If not, it shouldn't be here.

pros and cons of making my auth system a singleton class

I am facing a dilemma regarding OOP design of my application. Should I make the auth class a singleton or not. I see that kohana framework and zend framework use their auth classes as a singleton. What are the disadvantages of making the authentification class a singleton? What are the pros? Also the application I am building will be an enterprise application and it needs to scale, so will my auth system also scale if it will be a singleton?
Here would be some cons:
extremely hard to test, because code is tied to name of class
introduction of global state
inability to determine causes for an effect - unrelated methods can affect each other
scattering of authentication requests all over codebase
violation of LoD
You might benefit a lot from examining, at what stage and how exactly you authenticate the user ( do not confuse with authorization ). Also, this topic might be of some interest to you.
Update:
Here are few videos you might be interested in:
Clean Code Talks: Unit Testing
Clean Code Talks: Global State and Singletons
Clean Code Talks: Don't Look For Things!
PHP UK Conference 2011: Advanced OO Patterns
Avoid using the singleton and use it only in the case when a hardware has the limitation on one object -> resource per application. If you incorporate the singleton you will unable to exchange the auth class with something else in your system you will be stacked with it. Consider that tomorrow you could receive a new requirement which say you that you need to implement the authentication using a different logic, different connection and so on. Also though about how to test your system after using the singleton how will you mock it??
Don't go for Singleton! It's no better than glorified object-oriented namespace, in fact Singleton almost just as bad as using Global variables and only slightly better than using global function libraries (which in itself is also bad). It's better to send the created object to your classes.
Since PHP 5 objects passed around to other objects are passed by reference by default. They don't create a new instance (unless using clone keyword). This allows any sort of session info to be just passed as an object to other objects that need it.
Best thing I can recommend is make a class 'Session' that carries session specific information. Send this class to your MVC objects. This allows you to test the system without Session being present (or you can create a mockup state for that purpose). While passing one object to another makes them more coupled than ideal, as long as the class is primitive enough it can be easily created in other systems or parts of the app that use the same classes.
It also makes it easier to transfer states or sessions at any given time, even within the same request.
In PHP, the object doesn't stays in the memory once the request is completed.
So even if you make your object as Singleton, every request will have its own instance of that class.
But the the difference will come when object is being accessed multiple times in a single request. In that case, singleton has following advantages:
Prevents creating multiple redundant instances, so lesser memory usage for requests.
Shares the same data across multiple accesses.
Eg: Codeigniter's get_instance function is an implementation of Singleton Concept, whereby only one Codeigniter instance is used in each request.

Why use Zend_Registry instead of the Singelton pattern?

Why should I use Zend_Registry instead of the Singleton pattern?
My coworker and me recently had a discussion about this. His point was that we should use Zend_Registry for all consistent objects, but I wanted to use the singleton pattern, since Zend_Registry just does the same, but wrapped.
I have a problem with code like this:
$list = Zend_Registry::get('database')->getList($sql);
Since theres a chance that database isn't in Zend_Registry. In cases of lazy loading, I would have to make my own registry with information about specific objects in my system. Like if the database takes specific parameters on loadtime, then it would have to know this.
I would instead use getInstance and then all the code would reside in the same object. Does that make sense?
Even though you phrased your question as an either/or, might I suggest a third alternative?
I try to avoid both singletons and Zend_Registry wherever possible, since they function, in effect, as globals. When a segment of code can reach into the global ether - via a call to a singleton or a global registry - to get something it needs, it creates a hidden - or at least, a non-explicit - dependency that makes things harder to debug and unit-test.
In contrast, I try to follow dependency injection advice, paraphrased as: "Give a component what it needs. Don't make it find what it needs."
I find that for most entities for which I might feel I need a registry/singleton - db connections, loggers, etc - I can create them at Bootstrap, store them in the Bootstrap registry and inject them into my controllers, usually during init() using $this->getInvokeArg('bootstrap')->getResource('myResource'). Only controllers reach back into the Bootstrap. Then, any models or services that need these dependencies get them passed-in explicitly by the controller, either via constructor or by setter injection.
A hybrid approach to which I do sometimes fall back is to design my service/model classes with getters/setters for these dependencies - getDbAdapter() and setDbAdapter(); getLogger() and setLogger(), etc. The getter lazy-loads from the global registry - whether some singleton or by Zend_Registry, throwing exceptions when they are not where I expect them to be. In that sense, it is similar to what you are suggesting. It does violate the purist dependency injection philosophy. But at least the presence of the getter/setter methods explicitly demonstrates that there is a dependency and allows me to mock it out or to provide non-default implementations.
It does for simple blog or something. Otherwise you're stuck with only one DB instance. And that's NOT what you want in the long run. You may want to connect to other server (to log errors to central db, to import products from someone, ...) or connect as different user (for security reasons - you don't want your API to have access to admin_users table, but you still need to connect to it to check if user is valid in the first place).
You can do one-purpose registers (My_Db_Admin, My_Db_ReadOnly, ...) but that does not make much sense to me. Using registry you're not stuck with one instance. You can create one outside registry and work with it for a while and then trash it ;)

How can I make my objects/classes more portable?

From my basic understanding in Object Oriented coding, PHP in my case, you want to make all your classes pretty much independent of one another. I have just started my object oriented application so it is a great time for me to make changes in it's early stages.
Here is my situation where I break this rule or whatever you want to call it.
I have a sessions class that has a set method which lets me set variables to a php session and I have a view method which let's me view the value of a value that has already been set using the set method. So far it probably sounds OK but then on every page of my site I need to access session data or the session objects I should say. But then besides every page using the session objects, I also use them in all my classes that need the session value. I believe this is where I have messed up, because now all these other classes rely on the session class.
Any ideas on if this is wrong and if it is, what are some ways I can avoid it but still have access to the session data in the other classes and still have my classes be portable plug-n-play into other future applications?
This kind of relationship is called dependencies or coupling. You generally want to reduce coupling in any application (Object oriented or not). Just how to do it is perhaps the most important skill of a programmer, and can't really be summarised into a few rules.
However, at the most basic, you should try to distinguish between essential dependencies and accidental dependencies. The former is an un-solveable problem, so you shouldn't try. For example, if all your pages need access to the session, then you really can't help giving them that. But if they only need it some times, than you could try to factor your application so that this is addressed.
Another important point is to minimise the interfaces between components. If x is a subset of X and Y relies on x, then you shouldn't pass X. This is often a place where there is room for improvement.
Think about what those other classes need in order to function in terms of your domain model. Session data is an implementation detail that shouldn't affect how you design your other classes. The session object might have 100 properties, but not every class needs all 100 of those properties to work. They don't need to know if that data was persisted in sessions, cookies, flat-files, databases, or on a satellite outside earth.
A great resource I've found useful while designing classes is this book, and specifically chapter 6, "Working Classes" for your question.
You could add one level of abstraction making it WorkingClass > StoringMapper > Session, with WorkingClass only calling StoringMapper. As such, you could easily "map" the storing process to any other class than Session (for example DatabaseSession) without any changes to WorkingClass.
I've written some code for it in response to another question: Advice on framework design
Generally, one class using another is pure basic OO and what you'll want. Using Interfaces is a way to have your concrete logic isolated while letting other classes use this component in a uniform way. A simple and common way is to use a Factory or Abstract Factory instead of directly calling constructors. You should also have a look at the Inversion of Control and Dependency Injection (DI) paradigms. Here's a rudimentary example that could help you with your problem (but be aware, the author mixes up between Factories and DI).
A not to complex solution would be to extract an interface from your Session class. Think of what a caller would need from a session object. Then realize the interface in your class. You'll maybe want to make this class a Singleton (a class for which only one realization exists at runtime). Then, create a factory that instanciates your script's components. Pass the session instance to the components in the factoring method.

Categories