I am attempting to create a facade within laravel 4.1. I have created the facade, service provider and the class, to no avail. I followed numerous "how to's" including the advanced video for custom facades on Laracasts. No matter how many times I try, I end up with the exception of Non-static method Custom\Helpers\Helper::doSomething() should not be called statically
Here is my code...
HelpersServiceProvider.php
<?php namespace Custom\Helpers;
use Illuminate\Support\ServiceProvider;
class HelpersServiceProvider extends ServiceProvider {
public function register()
{
$this->app->bind('trial','Custom\Helpers\Helper');
}
}
HelpersFacade.php
<?php namespace Custom\Facades;
use Illuminate\Support\Facades\Facade;
class Helper extends Facade {
protected static function getFacadeAccessor()
{
return 'trial';
}
}
Helpers.php
<?php namespace Custom\Helpers;
class Helper {
public function doSomething()
{
return 'Hello';
}
}
I add the service provider to my app.php file and register the facade alias
'Custom\Helpers\HelpersServiceProvider',
'Helper' => 'Custom\Facades\Helper',
Then when I try to access it via a Static call (yes, I know it's not really static) or via the service provider directly I get the exception error.
Scratching my head on this one...
It looks like you have an incorrectly named class (or file):
HelpersFacade.php
class Helper extends Facade {
Additionally, your Helper class is in Helpers.php. Those need to match, also.
Related
I'm working with Laravel 5.8 and it's an Online Store project written by other programmers.
Basically I have faced something weird that never seen before.
Let's say we have this at a Controller method:
$payment = CourseRegistrationFacade::insertCourseRegisterInformation($courseId,$date,$memberId,$userId);
And then we goto the CourseRegistrationFacade and it goes like this:
class CourseRegistrationFacade extends BaseFacade
{
}
So the whole class is empty but it extends another Facade which is BaseFacade and it goes like this:
class BaseFacade extends Facade
{
protected static function getFacadeAccessor()
{
return static::class;
}
protected static function shouldProxyTo($class)
{
app()->bind(self::getFacadeAccessor(), $class)
}
}
And that's it !
I don't really know where the heal is insertCourseRegisterInformation !!
So if you know how this Facade works, please let me know...
Here is the full code of BaseFacade.php:
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class BaseFacade extends Facade
{
protected static function getFacadeAccessor()
{
return static::class;
}
public static function shouldProxyTo($class)
{
app()->bind(self::getFacadeAccessor(), $class);
}
}
Search in the code for:
CourseRegistrationFacade::shouldProxyTo(
Most likely in the service provider that line is somewhere registering that facade to some concrete implementation of a class. Then check the contents of the class (the argument passed to shouldProxyTo).
Inside that class there should be a method called insertCourseRegisterInformation.
The way facades work is they resolve the class out of the container and then call the method you call statically.
So for example, let's say you have a UserService.php with a method register() and that class is mapped to a UserServiceFacade.php. When you do UserServiceFacade::register(), __callStatic will get the facade accessor (actual class) from the container, then call the register() method of that class.
You can understand better by inspecting __callStatic inside Facade.php.
Essentially UserServiceFacade::register() is the same as doing:
$userService = app()->make(UserService::class);
$userService->register()
By using the facade you can hide the concrete implementation and could possibly switch it to something else in the future by just changing it in a single place.
I think there must be a Provider exists for that Facade which is initializing its associated class and insertCourseRegisterInformation method definition must be declared in it. Please find that provider and then you'll find its associated class from that Provider code. I think you can find all registered providers from config/app.php
These reference articles might help you.
Reference 1:
https://grafxflow.co.uk/blog/mvc/adding-global-custom-class-facades-laravel-5
Reference 2: http://www.expertphp.in/article/how-to-create-custom-facade-in-laravel-52
I've created a helper file in App folder named as Helper.php.
app/Helper.php
<?php
namespace App;
use Illuminate\Support\Facades\DB;
class Helper {
public function get_username($user_id)
{
$user = DB::table('users')->where('userid', $user_id)->first();
return (isset($user->username) ? $user->username : '');
}
}
app/Providers/HelperServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class HelperServiceProvider extends ServiceProvider
{
public function boot()
{
//
}
public function register()
{
require_once app_path() . 'Helper.php';
}
}
config/app.php
Inside the provider's array...
App\Providers\HelperServiceProvider::class,
Inside aliases array...
'Helper' => App\Helper::class,
Everything was working fine but now I have the following error.
ErrorException thrown with message "Non-static method Helper::get_username($user->id) should not be called statically
But when I add static keyword to function its works fine. What's the difference between static and non-static methods?
Aliases give you the possibility to access a facade in a blade template without adding it in the template (vie use statement). When calling a method via a facade, you call this method statically and the facade will call the object of the class containing this method.
In Laravel, it is usually more convenient to create a file containing helpers like Laravel does and to autoload that file via composer.
Please check here for more details
Without knowing how Laravel facades work, based on my PHP knowledge, I tried to extend Storage facade to add some new functionalities.
I have this code:
class MyStorageFacade extends Facade {
/**
* Get the binding in the IoC container
*
* #return string
*/
protected static function getFacadeAccessor()
{
return 'MyStorage'; // the IoC binding.
}
}
While booting service provider:
$this->app->bind('MyStorage',function($app){
return new MyStorage($app);
});
And facade is:
class MyStorage extends \Illuminate\Support\Facades\Storage{
}
When using it:
use Namespace\MyStorage\MyStorageFacade as MyStorage;
MyStorage::disk('local');
I get this error:
FatalThrowableError in Facade.php line 237: Call to undefined method Namespace\MyStorage\MyStorage::disk()
Also tried to extend MyStorage form Illuminate\Filesystem\Filesystem and got the same error in other way:
BadMethodCallException in Macroable.php line 74: Method disk does not exist.
Your MyStorage class needs to extend FilesystemManager not the Storage facade class.
class MyStorage extends \Illuminate\Filesystem\FilesystemManager {
....
}
A facade is just a convenience class that will convert a static call Facade::method to resolove("binding")->method (more or less). You need to extend from Filesystem, register that in IoC, keep your facade as it is, and use the Facade as a static.
The facade:
class MyStorageFacade extends Facade {
protected static function getFacadeAccessor()
{
return 'MyStorage'; // This one is fine
}
}
Your custom storage class:
class MyStorage extends Illuminate\Filesystem\FilesystemManager {
}
In any service provider (e.g. AppServiceProvider)
$this->app->bind('MyStorage',function($app){
return new MyStorage($app);
});
Then when you need to use it use it as:
MyStorageFacade::disk(); //Should work.
I encountered this issue using the repository pattern. Currently I use an interface, and a custom class to achieve it, then type-hint it into the controller's construct and because of Laravel, it will solve the repositories' dependencies automatically and recursively.
I also do this in a service provider:
$this->app->bind(path/to/repoInterface,path/to/implementationClass)
However, because of the way I coded these repositories, in order to avoid code duplication, I created an abstract class that has a common method to all these repositories. This class is as follows:
abstract class CommonRepo{
public function __construct(SomeModelClass model){}
public function commonMethod(){//Code here}
And my repositories have the following structure:
public class ExampleRepository extends CommonRepo implements ExampleRepositoryI{
public function __construct(){
parent::__construct();
}
}
Laravel doesn't like this, so its giving this error:
Argument 1 passed to path/to/repo/CommonRepo::__construct() must be an instance of path/to/model/SomeModelClass, none given, called in...
So, obviously is not resolving the dependency of the class CommonRepo, but it does resolve the dependencies on the normal repositories.
I'd like, if it's possible, to use type-hinting (the Laravel way) without having to do anything related to the new operator
How can I, then, resolve that class's dependencies ?
PD: Using Laravel 5.2
Parent constructor is called like normal function without touching dependency resolver so you should do one of two possibilities:
public class ExampleRepository extends CommonRepo implements ExampleRepositoryI
{
public function __construct(SomeModelClass $model){
parent::__construct($model);
}
}
or
public class ExampleRepository extends CommonRepo implements ExampleRepositoryI
{
public function __construct(){
parent::__construct(App::make(SomeModelClass::class));
}
}
nice question. I did some tinkering, though I don't know if this is what you're looking for. But you can dynamically create an instance of Eloquent model required by your repository class.
Let's say you have your User model class stored in app\Models\User.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
//
}
You then create a base abstract class for all of your repository classes: app\Repositories\BaseRepository.php. This is where you place all common functionalities for your repository classes. But rather than injecting the Eloquent instance through the constructor, you may add a method named getModel() to dynamically create an instance of Eloquent model for your repository.
<?php
namespace App\Repositories;
use ReflectionClass;
use RuntimeException;
use Illuminate\Support\Str;
abstract class BaseRepository
{
protected $modelNamespace = 'App\\Models\\';
public function getById($id)
{
return $this->getModel()->find($id);
}
public function getModel()
{
$repositoryClassName = (new ReflectionClass($this))->getShortName();
$modelRepositoryClassName = $this->modelNamespace . Str::replaceLast('Repository', '', $repositoryClassName);
if (! class_exists($modelRepositoryClassName)) {
throw new RuntimeException("Class {$modelRepositoryClassName} does not exists.");
}
return new $modelRepositoryClassName;
}
}
Now let's say you want to create a repository for your User model, and this user's repository must implement the following interface: app\Repositories\UserRepositoryInterface.php
<?php
namespace App\Repositories;
interface UserRepositoryInterface
{
public function getByEmail($email);
}
You create app\Repositories\UserRepository.php class and simply extend it from the BaseRepository class. Also don't forget to implement all specific implementations defined on UserRepositoryInterface.
<?php
namespace App\Repositories;
use App\Repositories\BaseRepository;
use App\Repositories\UserRepositoryInterface;
class UserRepository extends BaseRepository implements UserRepositoryInterface
{
public function getByEmail($email)
{
return $this->getModel()->where('email', $email)->firstOrFail();
}
}
This way you can bind the UserRepositoryInterface to it's implementation like so:
$this->app->bind(\App\Repositories\UserRepositoryInterface::class, \App\Repositories\UserRepository::class);
Finally you can freely inject the UserRepositoryInterface to a controller's constructor or methods. You can also resolve it via service container like this:
$userRepository = App::make(App\Repositories\UserRepositoryInterface::class);
$userRepository->getByEmail('john#example.com');
Of course there's a catch to this approach. The repository class should be started with the associated model, so the InvoiceRepository.php is dedicated for Invoice.php model class.
Hope this help!
This might help. You can listen in for when an object resolves and set attributes.
$this->app->resolving(CommonRepo::class, function ($object, $app) {
// Called when container resolves object of any type...
$object->commonObject = app(CommonObject::class);
});
Docs: https://laravel.com/docs/5.4/container#container-events
I have a service provider that I want to use to bind an instance of a class to the service container:
namespace App\Providers;
use Eluceo\iCal\Component\Calendar;
use Illuminate\Support\ServiceProvider;
class IcalProvider extends ServiceProvider
{
public function register()
{
$this->app->instance('iCal', function () {
return new Calendar(config('calendar.name'));
});
}
}
As I understand the documentation on binding an instance, this allows me to bind the key iCal to the service container so that later in my controller or service class I can type hint iCal and the instance created in the service provider will be used.
So I created a controller and tried to type hint my instance:
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class CalendarInviteController extends Controller
{
public function download(iCal $ical, $sessionId)
{
dd($ical);
}
}
But when I do I get the error:
Class App\Http\Controllers\iCal does not exist
Makes sense, as it applies it's looking for a class named iCal in the controller namespace which doesn't exist. There's not a use statement for the instance since iCal is just a text key, so I tried telling it to look at the root namespace thinking that may fix it:
public function download(\iCal $ical, $sessionId)
and I get the error:
Class iCal does not exist
When I read the section of the documentation on resolving from the service container it looks like the only thing I need to do in the controller is type hint to get the instance.
Am I misunderstanding the docs?
Update
I should also mention that I did add my service provider to my config/app.php file.
Also, when I create an interface, bind it to the service container instead, edit the vendor code to implement said interface, and inject that interface instead it works, but that requires that I edit the vendor code which I don't want.
As you see in the docs the method instance takes a key and an object instance to register in the container. So, if you want to register a specific instance in the container, the registration should be:
namespace App\Providers;
use Eluceo\iCal\Component\Calendar;
use Illuminate\Support\ServiceProvider;
class IcalProvider extends ServiceProvider
{
public function register()
{
//register a specific instance of the Calendar class in the container
$this->app->instance('iCal', new Calendar(config('calendar.name') );
}
}
This way you could get back the instance with:
$cal = \App::make('iCal');
If your purpose is to type-hint the class in the controller method, and you want to resolve the previous registered instance from the service container, you could do like this:
namespace App\Providers;
use Eluceo\iCal\Component\Calendar;
use Illuminate\Support\ServiceProvider;
class IcalProvider extends ServiceProvider
{
public function register()
{
//the key will be 'Eluceo\iCal\Component\Calendar'
$this->app->instance( Calendar::class, new Calendar(config('calendar.name') );
}
}
Now, in your controller:
namespace App\Http\Controllers;
//important: specify the Calendar namespace
use Eluceo\iCal\Component\Calendar;
class CalendarInviteController extends Controller
{
public function download(Calendar $ical, $sessionId)
{
dd($ical);
}
}
This way Laravel will see that you want a Calendar object and it will try to get it from the service container looking if exists a binding for this key: (because this is the namespace of the class you have specified in the controller)
Eluceo\iCal\Component\Calendar
and the binding exists! As you have bound this key to your service container in your service provider, so Laravel will return your registered instance.
In the code you provided, you tipe-hinted the class iCal, but the class didn't exist anywhere so Laravel wasn't able to instantiate the class
If you’re wanting to inject dependencies into your controller (which is good, so kudos!) then you need an interface name to type-hint on.
Usually you would have a generic interface, and then bind that interface to a concrete implementation. So you may have a calendar service interface, that’s bound to your iCal implementation. Something like this:
use Eluceo\iCal\Component\Calendar;
class CalendarServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('App\Services\Calendar', function ($app) {
return new Calendar(config('calendar.name'));
});
}
public function provides()
{
return ['App\Services\Calendar'];
}
}
So long as you register your service provider in your config/app.php file, you can now type-hint your calendar dependency in classes:
use App\Services\Calendar;
class InvitationController extends Controller
{
protected $calendar;
public function __construct(Calendar $calendar)
{
$this->calendar = $calendar;
}
}