What is difference between Laravel `app` method and `new` keyword? - laravel

I found that some developer use app(SomeService::class); while other use new SomeService(); in Laravel? Is there any difference between them?

Yes, the main difference is the ServiceContainer.
If you instantiate using app(YourService::class), the ServiceContainer will use reflection to inject in the class constructor the dependecies required.
So you don't have to explicit use all the dependencies needed.
It's well explained here.

Please check https://laravel.com/docs/5.7/providers.
Briefly speaking if you want to customize the class which you will use in runtime you can change it in provider (make it singleton or pass some arguments) and get in runtime via $app (if you have no opportunity to use DI). but when you making object vie new its only creates an instance.
Imagine that we have class A which receive 2 config parameters in construction.
So you need everywhere call new A($param1,$param2) . but using providers u can use DI to get instance of class A with already passed parameters or $app if u have no opportunity to use DI

Related

Is it possible to use Laravel 5 without facades?

I read that facades are not good. I have no idea if that is correct. I also read that Laravel uses a lot of them. Further, I read you can turn them off in Lumen. "Turn off" may not be the right word.
Do you have to use Laravel with facades? If I do not use the facades, does this mean I should probably not have chosen Laravel in the first place?
You aren't forced to use facades.
Check documentation at https://laravel.com/docs/5.1/facades
Just use app helper to get what you need.
app('router');
app('config')
or you can use IoC. There are a lot of ways.
In fact you don't need to use facades in your app. If you look at Facades class reference for each facade you can find class in this table. So for example instead of DB facade you can inject Illuminate\Database\DatabaseManager and you can use its method.
Using facade you would use:
DB:beginTransaction();
and injecting class and assigning it to class property you can write:
$this->db->beginTransaction();

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 to autoload multiple classes in Laravel 4 application?

I’ve created a workbench package in Laravel 4, which is name-spaced and has two directories: Models and Contexts. Somehow, Laravel is loading my models in my Models directory (I have a model in there called User), however, it doesn’t know about my classes in the Contexts directory.
I want to be able to use my context classes in my app’s controllers without specifying the whole namespace, so I thought I’d add them to Laravel’s IoC container. However, it seems I need to create a façade class for each class I wish to add to the container. This isn’t desirable if I have dozens of context classes, as it would mean creating an equal amount of façade classes too.
Is there a way in Laravel to bulk-add classes to its IoC container?
if you want to use one term facades for your classes the laravel way (e.g. MyModel::someAction()) then you have to create your facades. but i'd advise not to do so for so many classes.
if your classes inside contexts folder aren't found then you should check your composer.json file under the autoload entry or do a composer dump-autoload -o.
I'd just DI the classes within the constructor of the class that uses them, so you end up using $this->myService->someAction().
This should answer both Laravel 4 and 5.
First, you need to use the bind method Illuminate\Foundation\Application class, which serves to register binding in the service container. In the Laravel documentation you will find plenty of examples how to do that, but only for a single binding.
If you take a look a the implementation of bind method here or just the definition here, you will notice that this method accepts a string|array. This means you can provide multiple bindings as an array and register all of them in the container with their fully qualified class names. Something like this:
$this->app->bind(['\App\Acme\Service1', '\App\Acme\Service2', '\App\Acme\Service3', ...]
Having this in mind, you can easily get the classes in one namespace (directory) with a reflection, put them in array and use the above method to register them.
Revisiting this question some time later, I think the appropriate solution would be to autoload the classes using my package’s composer.json file, and then import classes using it’s FQN in controllers and other classes:
<?php
use Vendor\Package\Contexts\ContextClass;
class Laravel4Controller extends BaseController {
protected $context;
public function __construct(ContextClass $context) {
$this->context = $context;
}
}

No need to extend class/library in codeigniter

I would like to check if my assumption about codeigniter is right ?
We would normally extend a class when we are trying to include more functionality to the core, such as MY_Controller extends Controller, MY_Model extends Model etc...
But for example, if we are in the checkout library retrieving some checkout info(eg, product_id), we can just $this->load->library('product_lib',array('product_id'=>$product_id)) and we can easily $this->product_lib->product_name etc... from the checkout library right?
The $this->load thing is kind of equivalent to "hard code" checkout library to extend product_lib(class checkout_lib extends product_lib) to be able to use whatever methods/variables there is in the product_lib.
Please enlighten me.
In CodeIgniter $this->load is like having a resource manager (e.g. resourceManager->load("path/to/file")) and it takes care of loading the library, and passing any arguments you specify and such, easily allowing you to quickly get to using it.
So if you have a variable named product_name in your product_lib then yes calling $this->product_lib->product_name will be accessing that variable.
Really it just places the library into an array with the library name as the key and the instance of the library as the value so calling $this->product_lib is really calling something similar to $loadedLibraries['product_lib'] and returning the instance.
I hope that answers what you are asking, I'm quite tired and could have miss understood you question.
I think you misunderstood the OO paradigm and the way CI work.
$this->load is same with instantiate an object of the library/model, or load the helper file. CI have some sort of management to see if the helper/library/model already uploaded or not.
In other hand, the extends is used when defining a class, to tell PHP that the class will be inherit the parent class properties and method. A class is a blue print of object it will produce.
Maybe you can start by understanding the OO concept first. You can read this as a start, and see the reference used there.

Design Pattern for passing a translation object around? For PHP

I'm updating an php web application that is becoming multilingual, based on the Zend MVC framework, and I'm trying to figure out the best approach to passing the translation object to different classes/layers.
Most of my translation is done at the View level, but there are a few cases where I need to return status messages from custom libraries.
I could just create a property for the library and set the translator, but I'm wondering if there is a better way to integrate a translator object into an existing application?
Hold the users lanaguage in a Memento, and pass that through the program logic, when you need to do that translation use it identify the language.
If using Zend_Translate, it's best option to use register.
Zend_Registry::set('Zend_Translate', $translate);
This way all classes can find it automatically (Zend_Form, Zend_Validate, ...)
You could always instantiate the translator in the bootstrap.php so it is available to all classes as a global. That's how I'd do it since you probably need to use it everywhere. It isn't elegant, but it keeps you from having to add code wherever a class needs to throw an exception or return an error message.
If you don't have that many controllers setup can you not extend the base controller and instantiate the translator there? It should be available for use throughout the system then.
Something like this to extend:
<?php
class BaseController extends Zend_Controller_Action
{
public function init()
{
//setup translation object
}
}
?>
You might want to consider to use a dependency injector container, where the translator is an entry that you pass to the objects you need, without manually constructing the object. That way you can easily test and make more high quality (and testable) code
See other question here
How to use dependency injection in Zend Framework?
or this article about plugging ZF 2 DI into ZF1
http://adam.lundrigan.ca/2011/06/using-zenddi-in-zf1/

Resources