Lumen (Laravel) include library & use class in Controller - php

I have a question! I have a library, whenever I need to call, I'll include it into & new Class() like the link below.
Now, I want to include it to use with Lumen framework & call usually inton Controller, then how to register service, class in Lumen to make it comfortable so that when needing, just call new FileMaker();
http://laravel.io/bin/E3d9x
Thank you so much!

What you're looking for is a Service Provider. Instead of including files in your Controllers, and then new'ing up instances of a class it is better to register the class within a service provider and then resolve the object out of the IoC container.
An example of how you can register a provider:
public function register()
{
$this->app->singleton('Full\Vendor\Namespace\FileMaker', function($app) {
return new FileMaker('someparameters');
});
}
Doing it this way means that you can inject dependencies into your Controllers and Laravel, or Lumen in this case will automatically resolve the object without you needing to instantiate the object.
For example, in your controller:
public function someControllerMethod(FileMaker $filemaker)
{
// The $filemaker instance is available to use
}

Related

Symfony Components without the full stack framework

I'm using Symfony DI, Http, Kernel, Routing in my project following Create your own PHP Framework (https://symfony.com/doc/current/create_framework/index.html). It's fine and ok with is_leap_year App demo purpose.
I'm trying to figure out how I can inject services and container, into a custom controller defined in routes using only Symfony components, not framework bundle.
container.php
// add demo service into the service container
$containerBuilder->register('demo.service', '\Demo\DemoService');
// add dependent service into the controller container
$containerBuilder->register('dependent.controller', '\Demo\DemoController')
->setArguments([new Reference('demo.service')]);
// fetch service from the service container
// Echoing Works fine! But no service in controller
//echo $containerBuilder->get('dependent.controller')->helloWorld();
App.php
// nok with dependency
$routes->add('hello', new Routing\Route('/hello', [
'_controller' => 'Demo\DemoController::helloWorld',
]));
// ok with no dependency
$routes->add('hello2', new Routing\Route('/hello2', [
'_controller' => 'Demo\DemoService::helloWorld',
]));
And DemoController.php
<?php declare(strict_types=1);
namespace Demo;
class DemoController
{
private $demo_service;
public function __construct(\Demo\DemoService $demoService)
{
$this->demo_service = $demoService;
}
public function helloWorld()
{
return $this->demo_service->helloWorld();
}
}
Returns
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Demo\DemoController::__construct(), 0 passed
How can I get this working? Or, how can i inject container into the Controller Constructor ?
Example here https://github.com/Monnomcjo/symfony-simplex
You actually got pretty close so well done there. I think you mixed ContainerAwareInterface with the ContainerControllerResolver suggestion. Two different concepts really. Looks like you also tried making your own ControllerResolver class but you did not update container.php to use it. In any event, there is no need for a custom resolver at this point.
I also accidentally misled you with the suggestion that there was a service called 'container'. It is actually called 'service_container'.
# container.php
$containerBuilder->register('container_controller_resolver', HttpKernel\Controller\ContainerControllerResolver::class)
->setArguments([new Reference('service_container')]);
$containerBuilder->register('framework', Framework::class)
->setArguments([
new Reference('dispatcher'),
new Reference('container_controller_resolver'), // Changed
new Reference('request_stack'),
new Reference('argument_resolver'),
//new Reference('demo.service'), // No need for these
//new Reference('dependent.controller'),
])
;
Also, by convention, some of the framework services use id's like 'framework' or what not. But most of the time your application level stuff should just use the class name as the service id. In particular your need to use the controller class name to allow the ContainerControllerResolver to find it. It will also be useful when you venture into using the automatic wiring capabilities of the container.
// add demo service into the service container
$containerBuilder->register(\Demo\DemoService::class, \Demo\DemoService::class);
// add dependent service into the controller container
$containerBuilder->register(\Demo\DemoController::class,\Demo\DemoController::class)
->setArguments([new Reference(\Demo\DemoService::class)]);
And that should do it. Enjoy.

Laravel Structure - dependency injecting a controller

I have a laravel app and have created a SocialMediaController to get the latest posts from twitter and instagram and store them in the database.
I need them to be universally accessible and know I can access it via the IOC.
public function doSomething(App\Http\Controllers\SocialMediaController
$SocialMedia) {
}
However if feels wrong to inject a controller like this. What is be best way to wrap up these methods for global use?
It seems like you want to share some logic you have in the SocialMediaController with another controller, right?
Instead of trying to pass a controller instance to the controller action using the service container, you may move the current logic to a service. Refer to Service Container and Service Providers in the Laravel docs on how to create your own services.
Another way to achieve that is using a trait. Check this answer on how you can do that https://stackoverflow.com/a/30365349/1128918. You would end up with something like this:
trait SocialFeeder {
public function getLatestFromTwitter() {
...
}
}
And, then, you can use that new trait with your controllers:
class SocialMediaController extends Controller {
use SocialFeeder;
public function doSomething() {
...
$tweets = $this->getLatestFromTwitter();
...
}
}

Use of service providers within controllers in Laravel 5.2

As for the title I've googled about two hours searching for a efficient answer and read repeatedly the official documentation, but without any step further, considering I'm relatively new to the framework. The doubt arise while searching for a correct way to share some code between controllers and i stumbled in service providers, so:
I've created say a MyCustomServiceProvider;
I've added it to the providers and aliases arrays within the app.php file;
finally I've created a custom helpers class and registered it like:
class MyCustomServiceProvider extends ServiceProvider
{
public function boot()
{
//
}
public function register()
{
$this->app->bind('App\Helpers\Commander', function(){
return new Commander();
});
}
}
So far, however, if I use that custom class within a controller I necessarily need to add the path to it through the use statement:
use App\Helpers\Commander;
otherwise I get a nice class not found exception and obviously my controller does not his job.
I suspect there's something which escapes to me on service providers! :-)
So far, however, if I use that custom class within a controller I
necessarily need to add the path to it through the use statement:
`use App\Helpers\Commander;`
otherwise I get a nice class not found
exception and obviously my controller does not his job.
Yes, that's how it works. If you don't want to use the full name, you can use a Facade instead.
Create the Facade class like this:
class Commander extends Facade
{
protected static function getFacadeAccessor() { return 'commander'; }
}
register the service:
$this->app->singleton('commander', function ($app) {
return new Commander();
});
add the alias to your config/app.php:
'aliases' => [
//...
'Commander' => Path\To\Facades\Commander::class,
//...
],
and use it like a Facade:
\Commander::doStuff();
On why your code still works, even when you remove the bind:
When you type-hint a parameter to a function, and Laravel does not know about the type you want (through binding), Laravel will do its best to create that class for you, if it is possible. So even though you didn't bind the class, Laravel will happily create a instance of that class for you. Where you actually need the binding is when you use interfaces. Usually, you'd not type-hint specific classes but a interface. But Laravel can not create a instance of an interface and pass it to you, so Laravel needs to know how it can construct a class which implements the interface you need. In this case, you'd bind the class (or the closure which creates the class) to the interface.

How to override View::make() in Laravel 4?

I would like to override the default View::make() method in Laravel, which can be used to return a view-response to the user.
(I think) I've already figured out that this method is stored inside Illuminate\View\Factory.php, and I've been reading about IoC container, while trying to make it work using some similar tutorials, but it just won't work.
I've already created a file App\Lib\MyProject\Extensions\View\Factory.php, containing the following code:
<?php namespace MyProject\Extensions\View;
use Illuminate\View\Factory as OldFactory;
class Factory extends OldFactory {
public static function make() {
// My own implementation which should override the default
}
}
where the MyProject folder is autoloaded with Composer. But I don't know how to use this 'modified' version of the Factory class whenever a static method of View (in particular View::make()) is being called. Some help would be great!
Thanks!
The call to View::make is, in Laravel speak, a call to the View facade. Facades provide global static access to a service in the service container. Step 1 is lookup the actual class View points to
#File: app/config/app.php
'aliases' => array(
'View' => 'Illuminate\Support\Facades\View',
)
This means View is aliased to the class Illuminate\Support\Facades\View. If you look at the source of Illuminate\Support\Facades\View
#File: vendor/laravel/framework/src/Illuminate/Support/Facades/View.php
class View extends Facade {
/**
* Get the registered name of the component.
*
* #return string
*/
protected static function getFacadeAccessor() { return 'view'; }
}
You can see the facade service accessor is view. This means a call to
View::make...
is (more or less) equivalent to a call to
$app = app();
$app['view']->make(...
That is, the facade provides access to the view service in the service container. To swap out a different class, all you need to do is bind a different object in as the view service. Laravel provides an extend method for doing this.
App::extend('view', function(){
$app = app();
// Next we need to grab the engine resolver instance that will be used by the
// environment. The resolver will be used by an environment to get each of
// the various engine implementations such as plain PHP or Blade engine.
$resolver = $app['view.engine.resolver'];
$finder = $app['view.finder'];
$env = new \MyProject\Extensions\View($resolver, $finder, $app['events']);
// We will also set the container instance on this view environment since the
// view composers may be classes registered in the container, which allows
// for great testable, flexible composers for the application developer.
$env->setContainer($app);
$env->share('app', $app);
return $env;
});
Notice this is more than just instantiating an object. We need to instantiate it the same way as the original view service was instantiated and bound (usually with either bind or bindShared). You can find that code here
#File: vendor\laravel\framework\src\Illuminate\View\ViewServiceProvider.php
public function registerFactory()
{
$this->app->bindShared('view', function($app)
{
// Next we need to grab the engine resolver instance that will be used by the
// environment. The resolver will be used by an environment to get each of
// the various engine implementations such as plain PHP or Blade engine.
$resolver = $app['view.engine.resolver'];
$finder = $app['view.finder'];
$env = new Factory($resolver, $finder, $app['events']);
// We will also set the container instance on this view environment since the
// view composers may be classes registered in the container, which allows
// for great testable, flexible composers for the application developer.
$env->setContainer($app);
$env->share('app', $app);
return $env;
});
}
You can test if your binding worked with code like this
var_dump(get_class(app()['view']));
You should see your class name. Once your sure the binding has "taken", you're free to redefine whatever methods you want.

How to extend Laravel's Auth Guard class?

I'm trying to extend Laravel's Auth Guard class by one additional method, so I'm able to call Auth::myCustomMethod() at the end.
Following the documentation section Extending The Framework I'm stuck on how to exactly do this because the Guard class itself doesn't have an own IoC binding which I could override.
Here is some code demonstrating what I'm trying to do:
namespace Foobar\Extensions\Auth;
class Guard extends \Illuminate\Auth\Guard {
public function myCustomMethod()
{
// ...
}
}
Now how should I register the extended class Foobar\Extensions\Auth\Guard to be used instead of the original Illuminate\Auth\Guard so I'm able to call Auth::myCustomMethod() the same way as e.g. Auth::check()?
One way would be to replace the Auth alias in the app/config/app.php but I'm not sure if this is really the best way to solve this.
BTW: I'm using Laravel 4.1.
I would create my own UserProvider service that contain the methods I want and then extend Auth.
I recommend creating your own service provider, or straight up extending the Auth class in one of the start files (eg. start/global.php).
Auth::extend('nonDescriptAuth', function()
{
return new Guard(
new NonDescriptUserProvider(),
App::make('session.store')
);
});
This is a good tutorial you can follow to get a better understanding
There is another method you could use. It would involve extending one of the current providers such as Eloquent.
class MyProvider extends Illuminate\Auth\EloquentUserProvider {
public function myCustomMethod()
{
// Does something 'Authy'
}
}
Then you could just extend auth as above but with your custom provider.
\Auth::extend('nonDescriptAuth', function()
{
return new \Illuminate\Auth\Guard(
new MyProvider(
new \Illuminate\Hashing\BcryptHasher,
\Config::get('auth.model')
),
\App::make('session.store')
);
});
Once you've implemented the code you would change the driver in the auth.php config file to use 'nonDescriptAuth`.
Only way to add (and also replace existing functions) is to create copy of Guard.php file in your project and in app/start/global.php add:
require app_path().'/models/Guard.php';
Of course it's ugly method, but I spent over hour to test all possibilities [how to change things stored in Session by Auth] and it always end with error:
... _contruct of class HSGuard requires first parameter to be 'UserProviderInterface' and get 'EloquentUserProvider' ...

Categories