Where to find Service Containers in a Laravel project? - laravel

Where can I find the Service Container in a Laravel project.
All the Service Providers are in single location, in the app/Providers directory, but where to find the Service Container?

Service container is a core component of Laravel framework that is ready for you to use as it is, you are not supposed to create your own service containers like you do, for example, with service providers.
You can imagine service container being an associative array where you can store dependencies (services) and logic of how to resolve them. Then you can use service container to give you what you need based on what is there using provided logic.
It would be easier to imagine that service container is a black box that is always available. Your app at first registers (puts) certain rules in there (for example, if someone wants an object that implements PriceCalculator interface then give him object of a class MyPriceCalculator). It is done in register() method of your service providers:
$this->app->bind('App\Contracts\PriceCalculator', 'App\Shop\MyPriceCalculator');
Then this black box is always available for you, so if you ever need PriceCalculator object (for example, somewhere in your cart controller to calculate price of some order) you can now instead of doing:
$calculator = new \App\Shop\MyPriceCalculator;
Ask service container to make you a proper one:
$calculator = app()->make('App\Contracts\PriceCalculator');
Note how we are asking service container to give us implementation of an interface and will in turn give us new App\Shop\MyPriceCalculator object because that is how we defined (registered) App\Contracts\PriceCalculator service earlier.
Using service container is a great way to manage all dependencies of your application since your code will be working with abstractions and how those abstractions are resolved will be always defined in one place (which means it's easier to maintain if you want to change something later on).
If you are new to Laravel I would recommend to skip service containers for now since it's a little bit more advanced topic and you are required to have a better understanding of dependency injection pattern to fully grasp it and use properly.
You can read official documentation here.

Related

MVC3, Unity Framework with multiple configurations

We have a multi-company capable site which requires unique business logic for each company. We are using constructor dependency injection in our controllers, but would need to swap the unity container being used based upon a user's company. I was thinking that you could examine the user's cookie before setting the container for the current HttpContext. Is this even possible?
It's very doable. What I'd do is set up a "master" container, and then a child container for each company. That way you have default configuration in one place, and then you can customer per company easily without having to reconfigure every time. Save the child containers in some easily indexed way (a dictionary of company -> container, perhaps).
Then, write an HttpModule implementation that runs early in the pipeline to figure out which company the request is for. Use that to figure out the appropriate container to use. And from there you're pretty much set.
I would be worried as a customer of your system that you're not isolating my data sufficiently; wouldn't want to leak information across customers and get sued.

Is there a way in OSGi to make sure only one things has access to a service at a time?

I have an interface that defines a device in a system. The devices are intented to be used by only one entity at a time. I would like to register each device as an OSGi service so others can access the devices through that mechanism (using Declarative Services or a service tracker). However, that mechanism as far as I know, allows all entities to request the same service.
Is there a way for only the first requester to get the service or using Declarative Services only have one service component become satisfied?
Use a ServiceFactory to implement the device service. You can then return a unique service object to each bundle and then use that object to serialize access. Alternately your ServiceFactory could return null to other bundles if there is any other bundle which currently has access to the service.
Using a ServiceFactory allows your service implementation to know what bundles are using the service and to exert some control over their use.
AFAIK you can't use DS to impose a single consumer policy.
At first glance a ServiceFactory might work and if it did would be the simplest way to go.
However there's one caveat:
"The Framework caches the value returned (unless it is null), and will return the same service object on any future call to BundleContext.getService for the same bundle. This means the Framework must not allow this method to be concurrently called for the same bundle"
So I think it will fail in the following scenario:
Given Bundle A, Service S and Bundle B;
A gets S, then A ungets S, Bgets S, then A gets S.
The framework's cache may well interfere and give A the cached S even thought it is already held by B.
The only alternative I can think of is to use a FindHook, though this a bit more low-level, and you'd probably want to implement the other hooks (EventHook, ListenerHook) for completeness.
Using the hooks you'll be able to mask the services availability to other bundles. Though as your hook will be holding state you'll want it in the same bundle as the device service so that it's impossible to stop the hook without stopping the device service's bundle.

MVCS - Model View Controller Service

I've been using MVC for a long time and heard about the "Service" layer (for example in Java web project) and I've been wondering if that is a real architectural pattern given I can't find a lot of information about it.
The idea of MVCS is to have a Service layer between the controller and the model, to encapsulate all the business logic that could be in the controller. That way, the controllers are just there to forward and control the execution. And you can call a Service in many controllers (for example, a website and a webservice), without duplicating code.
The service layer can be interpreted a lot of ways, but it's usually where you have your core business processing logic, and sits below your MVC architecture, but above your data access architecture.
For example, you layer of a complete system may look like this:
View Layer: Your MVC framework & code of choice
Service Layer: Your Controller will call this layer's objects to get or update Models, or other requests.
Data Access Objects: These are abstractions that your service layer will call to get/update the data it needs. This layer will generally either call a Database or some other system (eg: LDAP server, web service, or NoSql-type DB)
The service layer would then be responsible for:
Retrieving and creating your 'Model' from various data sources (or data access objects).
Updating values across various repositories/resources.
Performing application-specific logic and manipulations, etc.
The Model you use in your MVC may or may not come from your services. You may want to take the results your service gives you and manipulate them into a model that's more specific to your medium (eg: a web page).
I had been thinking of this pattern myself without seeing any reference to this any where else and searched Google and found your Question here :)
Even today there is not much any body talking about or posting about the
View-Controller Service Pattern.
Thought to let you know other are thinking the same and the image above is how I view how it should be.
Currently I am using it in a project I am working on now.
I have it in Modules with each layers in the image above with in it's own self contained Module.
The Services layer is the "connector" "middleman" "server side Controller" in that what the "client" side Controller does for the client, the "Service" does for the server.
In other words the Client side "Controller" only "talks" with the "Service" aka Server Side Controller.
Controller ---> Requests and Receive from the <----- Service Layer
The Service layer fetches or give information to the layers on the server side that needs it.
By itself the Service does not do anything but connect the server layers with what they need.
Here is a code sample:
I have been using the MVCS pattern for years and I didn't know anyone else did as I couldn't find any solid info on the web. I started using it instinctively if you like and it's never let me down for Laravel projects. I'd say it's a very maintainable solution to mid sized projects, especially when working in an agile environment where business logic changes on the constant. Having that separation of concern is very handy.
Saying this, I found the service layer to be unnecessary for small projects or prototypes and what not. I've made the mistake of over complicating the project when making prototypes and it just ultimately means it takes longer to get your idea out. If you're serious about maintaining the project in the mid term then MVCS is a perfect solution IMO.

How to provision OSGi services per client

We are developing a web-application (lets call it an image bank) for which we have identified the following needs:
The application caters customers which consist of a set of users.
A new customer can be created dynamically and a customer manages it's users
Customers have different feature sets which can be changed dynamically
Customers can develop their own features and have them deployed.
The application is homogeneous and has a current version, but version lifting of customers can still be handled individually.
The application should be managed as a whole and customers share the resources which should be easy to scale.
Question: Should we build this on a standard OSGi framework or would we be better of using one of the emerging application frameworks (Virgo, Aries or upcoming OSGi standard)?
More background and some initial thoughts:
We're building a web-app which we envision will soon have hundreds of customers (companies) with hundreds of users each (employees), otherwise why bother ;). We want to make it modular hence OSGi. In the future customers themselves might develop and plugin components to their application so we need customer isolation. We also might want different customers to get different feature sets.
What's the "correct" way to provide different service implementations to different clients of an application when different clients share the same bundles?
We could use the app-server approach (we've looked at Virgo) and load each bundle once for each customer into their own "app". However it doesn't feel like embracing OSGi. We're not hosting a multitude of applications, 99% of the services will share the same impl. for all customers. Also we want to manage (configure, monitor etc.) the application as one.
Each service could be registered (properly configured) once for each customer along with some "customer-token" property. It's a bit messy and would have to be handled with an extender pattern or perhaps a ManagedServiceFactory? Also before registering a service for customer A one will need to acquire the A-version of each of it's dependencies.
The "current" customer will be known to each request and can be bound to the thread. It's a bit of a mess having to supply a customer-token each time you search for a service. It makes it hard to use component frameworks like blueprint. To get around the problem we could use service hooks to proxy each registered service type and let the proxy dispatch to the right instance according to current customer (thread).
Beginning our whole OSGi experience by implementing the workaround (hack?) above really feels like an indication we're on the wrong path. So what should we do? Go back to Virgo? Try something similar to what's outlined above? Something completely different?!
ps. Thanks for reading all the way down here! ;)
There are a couple of aspects to a solution:
First of all, you need to find a way to configure the different customers you have. Building a solution on top of ConfigurationAdmin makes sense here, because then you can leverage the existing OSGi standard as much as possible. The reason you might want to build something on top is that ConfigurationAdmin allows you to configure each individual service, but you might want to add a layer on top so you can more conveniently configure your whole application (the assembly of bundles) in one go. Such a configuration can then be translated into the individual configurations of the services.
Adding a property to services that have customer specific implementations makes a lot of sense. You can set them up using a ManagedServiceFactory, and the property makes it easy to lookup the service for the right customer using a filter. You can even define a fallback scenario where you either look for a customer specific service, or a generic one (because not all services will probably be customer specific). Since you need to explicitly add such filters to your dependencies, I'd recommend taking an existing dependency management solution and extending it for your specific use case so dependencies automatically add the right customer specific filters without you having to specify that by hand. I realize I might have to go into more detail here, just let me know...
The next question then is, how to keep track of the customer "context" within your application. Traditionally there are only a few options here, with a thread local context being the most used one. Binding threads to customers does tend to limit you in terms of implementation options though, as in general it probably means you have to prohibit developers from creating threads themselves, and it's hard to off-load certain tasks to pools of worker threads. It gets even worse if you ever decide to use Remote Services as that means you will completely loose the context.
So, for passing on the customer identification from one component to another, I personally prefer a solution where:
As soon as the request comes in (for example in your HTTP servlet) somehow determine the customer ID.
Explicitly pass on that ID down the chain of service dependencies.
Only use solutions like the use of thread locals within the borders of a single bundle, if for example you're using a third party library inside your bundle that needs this to keep track of the customer.
I've been thinking about this same issue (I think) for some time now, and would like your opinions on the following analogy.
Consider a series of web application where you provide access control using a single sign-on (SSO) infrastructure. The user authenticates once using the SSO-server, and - when a request comes in - the target web application asks the SSO server whether the user is (still) authenticated and determines itself if the user is authorized. The authorization information might also be provided by the SSO server as well.
Now think of your application bundles as mini-applications. Although they're not web applications, would it still not make sense to have some sort of SSO bundle using SSO techniques to do authentication and to provide authorization information? Every application bundle would have to be developed or configured to use the SSO bundle to validate the authentication (SSO token), and validate authorization by asking the SSO bundle if the user is allowed to access this application bundle.
The SSO bundle maintains some sort of session repository, and also provides user properties, e.g. information to identify the data repository (of some sort) of this user. This way you also wouldn't pass trough a (meaningful) "customer service token", but rather a cryptic SSO-token that is supplied and managed by the SSO bundle.
Please not that Virgo is an OSGi container based on Equinox, so if you don't want to use some Virgo-specific feature, you don't have to. However, you'll get lots of benefits if you do use Virgo, even for a basic OSGi application. It sounds, though, like you want web support, which comes out of the box with Virgo web server and will save you the trouble of cobbling it together yourself.
Full disclosure: I lead the Virgo project.

Base class for windows service

My new project has a design in which there are number windows services for performing different tasks. I have been given a task to create base class from which all of the windows service will inherit. This base class will perform common functions like creating instances of other windows services by iterating through the config file (may be like Activator.CreateInstance), do event logging on onStart, onStop etc. and may contain some more functionality.
Before I start developing stuff, wondering if there is any pattern already in place or someone has good understanding of how to implement this kind of functionality.
Any help appreciated.
I forgot to mention I am using .Net 2.0 (C#), no option for wcf
Check "A simple windows service to host WCF or WF services", I really like it.
Look in your main method , when you create windows service and you will see that the routine is not call onstart and onstop, you can create each service by createinstance and give it as a paramater to ServiceBase.Run, in your case every service will not appear as a separate service, ServiceController is a great class to start and stop services too, use it if you need

Resources