I have just started exploring laravel but I have one confusion . I know how to create own custom function file and make it available globally using compose.json file but I was trying to figure out how laravel's helper function like route() , view() are accessible without including there source file and I can't find any auto discovery in composer.json file neither in any Service Provider .
PS : I have only checked in in Providers/ Directory.
Can anyone tell me how this thing works?
Through composer Laravel has defined which files should be autoloaded. With the line in the composer.json file in Laravel/framework it specifies what should be autoloaded.
It loads the following file.
You can create similar autoloaders if you prefer, but having to much logic in such helpers could easily become an anti pattern. As the logic, is a little more hidden than class based logic, when people have to look through your projet.
On your composer.json file on the root directory of your laravel app, look for the entry autoload.
This means all methods on those directories are autoloaded.
That is why if you have (newly) created a method / function within those directory and it doesn't work (or not found) as expected, you need to run composer dump-autoload to make sure that everything has been loaded.
That's also where I put my custom helper file:
"files": [
"app/Helpers/helpers.php"
]
All function here will then be available on all controllers, traits and views.
Related
I have module created in the basic project of yii2 and now i want to access or use that module another project/application of mine....
How can I achieve this.
please help me out here.
To use module in different apps there are 3 things you need.
The module must not be dependent on classes from core project. For any class that needs to be implemented by core project the module should define interface and depend on that interface instead of class itself.
The module should use different namespace than app and autoloader must know how to load classes from that namespace. (more about that later)
You have to add module in your config in same way you've added it in first project.
The points 1 and 3 are pretty much self-explaining. If are not sure how to add module in config see the yii2 guide.
Now back to the second point. While naive way of copying module over to second project would work it will turn maintaining the module into nightmare because each change would have to be done in each copy of module. So it's better to keep the code of module in one place and make it available for each project. There are multiple ways of doing that.
If you want to, you can turn your module into extension and make it publicly available through packagist as it was suggested by M. Eriksson in comments. After that you would simply add your extension through composer as any other dependency.
Composer also allows you to define and use private repositories if you don't want to publish your module at packagist. See composer documentation for more details.
The most trivial way is to simply put the code into separate folder outside of project. If you do that, you have to make sure that autoloaders in your projects are capable of finding the files locations to load classes. There are two options how to do that. In any case you will want to avoid conflicts with namespaces used by your project, that's why you need to use different namespace.
Let's assume that you've put your module files into folder /path/to/modules/myModule and all classes in your module belongs to namespace modules\myModule. You have to make sure that your webserver can access that folder and that it can run php scripts there.
First option is to use Yii's autoloader. That autoloader uses aliases to look for classes. If you add #modules alias and point it to /path/to/modules folder, the Yii autoloader will try to look for any class from modules\* namespace in /path/to/modules folder. You can add the alias in your config file (web.php, console.php or any other config file you use):
return [
// ...
'aliases' => [
'#modules' => '/path/to/modules',
// ... other aliases ...
],
];
The second option is to use project's composer.json file to set autoloader generated by composer to load your classes.
{
"autoload": {
"psr-4": {
"modules\\": "/path/to/modules"
}
}
}
You can find more info about this in composer's documentation.
Don't forget to run composer dump-autoload after you change autoload settings in your composer.json file to update the generated autoloader.
I've read a lot of questions on how to make helper methods in Laravel 5.1. But I don't want to achieve this via a Facade.
HelperClass::methodName();
I want to make helper methods just like on these methods Laravel Helper Methods like:
myCustomMethod();
I don't want to make it a Facade. Is this possible? How?
If you want to go the 'Laravel way', you can create helpers.php file with custom helpers:
if (! function_exists('myCustomHelper')) {
function myCustomHelper()
{
return 'Hey, it\'s working!';
}
}
Then put this file in some directory, add this directory to autoload section of an app's composer.json:
"autoload": {
....
"files": [
"app/someFolder/helpers.php"
]
},
Run composer dumpauto command and your helpers will work through all the app, like Laravel ones.
If you want more examples, look at original Laravel helpers at /vendor/laravel/framework/Illuminate/Support/helpers.php
To start off I created a folder in my app directory called Helpers. Then within the Helpers folder I added files for functions I wanted to add. Having a folder with multiple files allows us to avoid one big file that gets too long and unmanageable.
Next I created a HelperServiceProvider.php by running the artisan command:
artisan make:provider HelperServiceProvider
Within the register method I added this snippet
public function register()
{
foreach (glob(app_path().'/Helpers/*.php') as $filename){
require_once($filename);
}
}
lastly register the service provider in your config/app.php in the providers array
'providers' => [
'App\Providers\HelperServiceProvider',
]
After that you need to run composer dump-autoload and your changes will be visible in Laravel.
now any file in your Helpers directory is loaded, and ready for use.
Hope this works!
This is what is suggested by JeffreyWay in this Laracasts Discussion.
Within your app/Http directory, create a helpers.php file and add your functions.
Within composer.json, in the autoload block, add "files": ["app/Http/helpers.php"]. And run
composer dump-autoload.
I am attempting to create a sort of custom directory structure, my proposed structure is as follows
App/ - Contains all Laravel core code
Repo/ - Contains packages, each package contains Controllers, Views, Modals, Seeds and Migrations specific to that package
Is it possible via Composer or would it take a lot of core modification?
Controller routing in routes.php
Route::resource('account', '\Repo\Accounts\Accounts');
The first occurrence of accounts is the folder and the second being the class. I know I could write each directory seperetly then dump composer autoload, however when you have 30 seperate packages per app, it is a little time consuming. Am I missing something super straight forward?
This is possible with composer. Add inside of your composer.json:
"autoload": {
"classmap": [
// ...
],
"psr-4": {
"Repo\\" : "Repo"
}
},
Then you can use classes inside of the /Repo directory, and classes in there will reside in the \Repo namespace.
I created a modular system by using laravel 4.1 I have a tree scheme as follows:
app/
app/controllers/
app/modules/
app/modules/modulename/
app/modules/modulename/controllers/
app/modules/modulename/controllers/modulecontroller.php
app/modules/modulename/models/
app/modules/modulename/models/modulemodel.php
What I want to do is to call the model from a controller in app/controllers/ class.
How I can call that module and its model?
Make sure your /app/modules is added to your composer.json file's autoload : classmap and issue composer dump-autoload or php artisan dump-autoload. Then you can just create an instance like new ModuleModel or whatever name you gave your class. Though it's better to pass to your controller by dependency injection. This way your code will be easier to test because you can pass in stub data.
public function __construct(ModuleModel $module_model_instance) {
$this->module_model_instance = $module_model_instance;
}
I'd rather add this as a comment but have insufficient rep.
If everything is correctly autoloaded by composer in the PSR-0 (or 4) section, then you should just be able to reference it using it's namespace?
I sometimes need to run
composer dump-autoload
to refresh the autoloaded files, especially if using vagrant.
Hope this is helpful. I'm not sure if I've fully understood your problem.
I am trying to include the YouTube Analytics Service of Google but I can not access it through the Vendor folder.
include(app_path.'path/to/analytics/Google_YoutubeAnalyticsService.php')
It is not working, because it defaults to the App folder.
How can I get out of the App folder and into the Vendor folder (where the YouTube Analytics file is at)?
The error is {
include(C:\xampp\htdocs\mysite\app/path/to/analytics/Google_YoutubeAnalyticsService.php):
failed to open stream: No such file or directory
From where do you want to include that file ?
Place a reference to your file in composer.json autoload object:
"autoload": {
"files":["your_file_path"]
}
Run composer dumpautoload, and you'll have your file :)
Actually you have in the helpers function the path so basically the function base_path give the direction to the root of your project so
echo base_path() . '/vendor';
Should be the route to your vendor folder.
You can se all the documentation in
Helper Functions Laravel
Be sure that you are seeing the documentation of the laravel version that you are using (I put the link for the 4.2 version).
This question was asked a long time ago and the answers reflect that. Most the time now all you need to do is import it using the "use" statement if you installed it with composer. Composer will already reference all the important directories.
It should be something like this, but it will vary depending on the project.
use FolderNameUsuallyGitHubUserName\ClassNameorGitHubProjectName\Class;
That could include a base class as well as some exception classes.
use FolderNameUsuallyGitHubUserName\ClassNameorGitHubProjectName\ClassException;
Usually most packages if compliant with modern composer and php standards work in this fashion.