Explanation needed for laravel avoid using static access - laravel

I would like to more in depth knowledge about using static methods . I'm using laravel 5.2 framework for my application.
In my application mostly i have used static functions For example i have model class name like post and method name is get_post() and its declared as static only if i missed static keyword in laravel it throws error
class Post extends Eloquent(){
public static function get_post(){
return DB::table('post')->get();
}
}
In my controller i will call this above method
Post::get_post()
How could i avoid to call this method as static ? as per the PHPMD 1.4.0 rule
Anyone please explain clearly.

Laravel's Eloquent is called via the static method, so I'm not sure how to avoid this. By the way, instead of the functions you wrote, you can of course write
Post::all();
Another abstraction possibility is to use the Repository Pattern, where the Controller doesn't call the Model's functions directly, but rather something like
$activePosts = $postRepository->getActiveAndApproved();
where the $postRepository would do some of the heavy lifting on Laravel's Eloquent model doing e.g. ->where('something', true) and stuff like that - Symfony has this already a bit stronger included in their framework.
See https://bosnadev.com/2015/03/07/using-repository-pattern-in-laravel-5/ for more detailed instructions.
Seeing also that Laravel uses Facades a lot, which is a simplified way to access functions in the service container (e.g. see config/app.php or https://laravel.com/docs/5.2/facades for more infos), it might be difficult to avoid static function calls.

Related

Does Cache work in an API route and should we use it?

I am creating an API. In this API I am accessing a (permissions) table from a database multiple times, in middleware as well as in controllers. I was thinking, instead of accessing the database multiple times, why don't I call it once and use it multiple times. After calling it once, I could store it in the cache within a service provider. But I am not sure if it is a good way to go because API routes don't load all the services like session.
There are other ways like storing data into the config. Or create a class and make a facade for it and then call it when ever it is needed. But I am curious if the cache would work in API routes and would it be a good idea?
Okay with the advice of #lagbox I created a dead simple class.
namespace App\Helpers;
use App\Permission;
class Provide
{
public $permissions = [];
function __construct() {
$this->permissions = Permission::whereNotNull('route_name')->get();
}
}
This may vary, it's just a class that will keep some collection data in it. I named it provide to keep it generic, just in case that I could need other data than permission in the future. Of course this class could be more detailed but just for storing and returning permissions it is enough.
Then I bound it as a singleton in my AppServiceProvider to run it only once.
public function register()
{
$this->app->singleton('App\Helpers\Provide', function ($app) {
return new \App\Helpers\Provide();
});
}
and when I need it I call it like
$provide->permissions->toArray()
All the features of the collection are available everywhere from the beginning to the end. Yes that may look like an overkill or an abuse of IoC but this über simple approach is in my case a superb solution.

Need Understanding of Laravel Core Feature

I am a beginner starting out in laravel 5.2 and I think these concepts below should be explained more straight forward than just reading documentation.
Service Providers
Service Container
Contracts
Facades
I think a good explanation and examples that can really help beginners understand how these 4 concepts fit together in the framework.
Service provider :
The so called service providers are the heartbeat of your Laravel application. They are the central element of the initialization process where all the relevant and required code is loaded by PHP. This includes all the essentials from the framework itself, but also any own and custom code you need to load.
Inversion of Control, or IoC :
Can't be explained easly (i only have few ideas about this im not a pro)
Facades :
The Facade pattern is a software design pattern which is often used in object oriented programming. A facade is, in fact, a class wrapping a complex library to provide a simpler and more readable interface to it. The Facade pattern can also be used to provide a unified and well-designed API to a group of complex and poorly designed APIs.
A Laravel facade is a class which provides a static-like interface to services inside the container. These facades, according to the documentation, serve as a proxy for accessing the underlying implementation of the container’s services.
MORE
Contracts :
LARACASTS FREE VIDEO
I know this is not enough! what you are asking is complicated stuff a single answer can't be enough
Ok, so first I agree with the others that laracasts is an amazing resource, that will really go into greater detail and break things down very simply.
That being said, the brief overview is as follows:
Service Container (IoC container) is a laravel core process that allows you to load objects with their dependencies gracefully. For example, If I have a controller method like this:
public function update(Request $request, $id)
{
...
}
IoC container is smart enough to resolve the Request and load up all the dependencies associated with the Request class to make sure it gets instantiated properly.
It also allows you to instantiate classes without having to fully pass along all the dependencies as follows:
class ProductRepo(Product $product)
{
public function get($id)
{
...
}
}
I can reference this class without loading it with dependency injection as follows: (make sure to pass in full namespace)
app('App\ProductRepo')->get($id);
This allows me to not have to pass in a Product Object, Laravel is smart enough to resolve the Product object because the IoC container is doing the magic behind the scenes.
Service Providers are a place for you to lace in custom behavior when booting up or instantiating a class. For example, Laravel by default uses a class called the EventServiceProvider. This class's job is to configure the Event system in Laravel to make sure to include all the custom event listeners you create. So if I wanted to make sure that when the EventDispatcher is being loaded up, it brings in all the necessary dependencies.
Contracts are really simple. They are just an allusion to php object oriented concept of Interfaces. This concept states that there are classes that establish rules. For Example:
interface SearchableInterface
{
public function search($data);
}
class BinarySearch implements SearchableInterface
{
public function search($data)
{
...
}
}
This states that any class that implements the SearchableInterface, must have a function search that accepts one parameter. This creates a 'contract' that any classes that implement the SearchableInterface will have to have this function, or the application will throw an error.
This is great for using interchangeable pieces (siblings) and not having to worry that the class is missing a function you need.
Last but not least is the Facade. I love facades. In a nutshell all this is doing is creating a static representation of a class that was not defined statically. So lets say I have a class that will get a document from S3.
class S3
{
public function get($file)
{
...
}
}
Without a facade you would first have to instantiate and then call get on the class in order to get something from S3.
$s3 = new S3;
$s3->get('myAwesomeFile');
Laravel allows you to easily register Facades so that you can just use this statically for readability and convenience.
S3::get('MyAwesomeFile');
All of this has been an over-simplification of each concept, but goes into some detail about some of the basics of each concept. Hope this helps!

Best approach for Dependency Injection in Laravel 5 package

I am developing a package for Laravel 5, and now I need to benefit from dependency injection to have a more scalable and relaible application, I don't know which approach is the best to take and why, this is a piece of my code and I need to injected the Lang class dependency
class MyController extends \App\Http\Controllers\Controller
{
public $text;
public $lang;
public function __construct()
{
// Some codes here
}
public function myFunction(){
$this->text = \Lang::get('package::all.text1');
}
}
In this link http://laravel.com/docs/4.2/ioc 2 approaches are suggested, Basic Usage and Automatic Resolution based on my understanding from the link
taking the first approach I need to add
App::bind('lang', function($app)
{
return new \Lang();
});
to the register part of application and then in the function I'll have something
like this :
public function myFunction()
{
$lang = \App::make('lang');
$this->text = $lang::get('package::all.text1');
}
The other way is to modify the constructor like
public function __construct(Lang $lang)
{
$this->lang = $lang;
}
And then instantiate object from Class like
$myController = App::make('MyController');
Which way is the better way to take for, considering that this class is a Controller and it will be called in the routes file, or please correct me if my understanding from the link is not right. please also inform me why you suggest any of those approaches.
It should be noted that using local IoC resolution ($app->make() stylee) is not much better than using the facades directly (Lang::get() stylee) - you're still very much relying on Laravel's specific classes without really making your code explicitly state that it needs these exact classes. So the general advice is to, as much as possible, code to an interface if you want your code to be as portable as possible.
Of course there are a couple of big downsides to this currently in PHP development:
These interfaces are not generally defined (except the PSR-3 LoggerInterface interface) so you still have to rely on a particular instance of the interface (in this case, Laravel's).
If you decide to make your own generic interface (or the FIG eventually creates some of these), the classes that Laravel provides for translation (for example) don't implement it anyway, so you then need to subclass the existing ones just to make it look like it implements your own interface. But hey, that's the current best practice, so I guess if you wanna be using the current best practices, code to an interface, and don't worry for the time being that the interface you're coding to is Laravel-specific.
But anyway, here are my thoughts on your specific question. First off I should say that I haven't actually used Laravel 5 yet (just the 4s), but I have generally followed its development.
If the class I am coding will use a given dependency quite a lot or as a core part of how the class works I will use constructor dependency injection. Examples here are the Request or some Repository class in a controller, or a business logic class in a console command class.
If what I need I only need for a specific purpose (maybe redirecting from a controller and needing to generate a URI) I will resolve a local version from the IoC container ($this->app->make()) and then use that. If I were using Laravel 5 and the method was called by Laravel directly (e.g. a controller's action method) I may use method injection for this, I'm not 100% sure.
As a final note, the general advice is that if your constructor method signatures get too big due to a lot of dependencies:
It's time to have a look at if your code relies too much on external dependencies. Maybe some of the functionality of your class can be extracted to its own class that splits the dependencies between the two.
You should consider using setter methods rather than constructor injection - so instead of accepting a Request object, you have a $class->setRequest() method. The downside of doing this is that you need to tell Laravel's IoC container how to instantiate your object (i.e. that these setters must be called). It's not that big a deal but something worth noting.
Relevant links:
Laravel 5's IoC article
Laravel 5's Controller injection advice

Laravel constants in class Facades

I have a class called Awesome and have used the ServiceProvider and the Facade to register it to the app. Now I can use it as Awesome::Things().
I want to add constants to this class, so I tried
<?php namespace Helper\Awesome;
class Awesome()
{
public static $MOVIE = 'I love the Lego Movie!";
}
but when I call Awesome::$MOVIE, I get Access to undeclared static property: Helper\\Aesome\\Facades\\AwesomeFacade::$MOVIE
Can someone help?
The short version is -- you don't really want to do that. Laravel facades aren't mean to be used like normal classes, and if your application uses them that way you'll likely confuse future developers.
Warning out of the way. When you create a "facade" in Laravel, you're actually creating a class alias. When you added Awesome to the alias list in app/config/app.php, at some point code like the following ran
class_alias('Helper\Aesome\Facades\AwesomeFacade','Awesome');
That means whenever you use a global non-namespaced class Awesome, PHP substitutes Helper\Aesome\Facades\AwesomeFacade. If you wanted to add constants, you'd need to add them to this class.
Laravel's able to pass through methods because of the base Facade class implements a __callStatic method that passes on your call to the actual service implementation object. Facades don't pass on static constant access. Additionally, PHP does not (appear to?) have similar magic methods for passing along requests for constants.
If you're curious about the in depth version of this answer, I'm currently writing a series on Laravel's object system, including some in-depth information about the facade implementation.

How do I access the static methods of a custom class in Kohana?

I have a user class with static methods getById and getByUsername
I have the class in the application/libraries folder
How do I call the classes from a controller?
Theory 1:
$this->user = new User();
$this->user::getById;
Theory 2:
$user = new User();
$user::getById;
or is there a clean way of doing it much like how Kohana helpers do it; much like:
text::random();
here's what I am trying to accompplish:
I want to call a static mehthod in the user library from my controller
In PHP you usually include the file (User.php) and the static methods are ready
User:getById
but then how would I do the same thing in an MVC framework?
shall I do an include too?
Like include ('User.php');?
User::getById();
and
User::getByUserName();
Edit: In response to your question edit, generally frameworks have an auto-loading mechanism that will find and load a class file for you once you reference that class. So when you type User::getById(), the PHP interpreter will see that it needs to load the User class (if it hasn't been loaded already), and run the autoloading procedure to find the correct code to include.
I've never used Kohana, but I would be quite surprised if it didn't use some form of autoloading. If it does not, then yes, a simple include('User.php') will be enough to make the static method calls to User work.
The confusing thing is Kohana's convention of writing "helper" classes with lowercase names.
Your user php file will probably all ready be loaded if your using it as a model, so you can use zombat's suggests of User::getById();.
I don't like to follow their naming convensions for helpers or libraries and instead do:
require_once(Kohana::find_file('libraries', 'user_utils', TRUE, 'php'));

Resources