How can I write an accessible class in the whole of project? - php

I use Laravel framework and this is my current directory:
As you see, there is a class named Log (the one I've selected). Now I need to make it global. I mean I want to make it accessible in everywhere and be able to I make a object (instance) of it in following files:
All files of classe folder
All controller
web.php file of
All file of views
Anyway I want to be able to make a instande of it and call its methods everywhere like this:
$obj = new Log();
$obj->insert($message);
How can I do that?

You can create global Laravel helper:
if (! function_exists('log')) {
function log($message)
{
(new Log)->insert($message);
}
}
Put it in helpers.php and add this to composer.json to load the helpers file:
"autoload": {
....
"files": [
"app/someFolder/helpers.php"
]
},
Then you'll be able to use this helper globally:
log('User added');
In views:
{{ log('User added') }}
Update
#stack, you're using wrong syntax for JSON (screenshot in comments), here's correct one:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Helpers/helpers.php"
]
},

Related

Creating and accessing custom module's REST routes in Prestashop 1.7.5

I am trying to create a custom controller in my Prestashop 1.7.5 module.
I created a custom controller:
# /var/www/html/modules/Profit/src/controller/ProductProfitController.php
namespace Profit\Controller;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
use Symfony\Component\HttpFoundation\JsonResponse;
class ProductProfitController extends FrameworkBundleAdminController {
public function test() {
return JsonResponse();
}
}
I loaded the class with my composer.json file:
# /var/www/html/modules/Profit/composer.json
{
"name": "company/profit",
"description": "Moduł opłacalności",
"authors": [
{
"name": "Name",
"email": "Email"
}
],
"require": {
"php": ">=5.6.0"
},
"autoload": {
"psr-4": {
"Profit\\Controller\\": "src/controller/"
},
"classmap": [
"Profit.php",
"src/"
],
"exclude-from-classmap": []
},
"config": {
"preferred-install": "dist",
"prepend-autoloader": false
},
"type": "prestashop-module",
"author": "Name",
"license": ""
}
I added a route in my module's routes folder
# /var/www/html/modules/Profit/config/routes.yml
update_price_cut:
path: Profit/price-cut
methods: [GET]
defaults:
_controller: 'Profit\Controller\ProductProfitController::test'
Yet I do not know how to access that route. I tried:
localhost:8001/admin-dev/Profit/price-cut
localhost:8001/modules/Profit/price-cut
localhost:8001/modules/Profit/Profit/price-cut
localhost:8001/Profit/price-cut
None of these work. Every single one of them leads to a 404 error.
Is this the proper way of creating routes to your module's custom controller? How can I fix this?
NOTE: This controller is supposed to be a BackOffice controller. I want to use it to update products' details from the default PrestaShop product list.
Try $this->generateUrl('update_price_cut') within admin controllers. It will generate a correct route to your controller. Or if you need it in a different place you can create own service and use it. More information you can find here
The existing answer didn't help me much, plus it doesn't mention the actual URL, for people stumbling on here through Google.
Setup
# /config/routes.yml
my_route_name:
path: /my_project/my_path # Leading / can be omitted
methods: [GET]
defaults:
_controller: 'Me\MyProject\Admin\Controllers\MyController::indexAction' # This can point to any class and any public method.
// my_project/admin/controllers/MyController.php
class MyController extends FrameworkBundleAdminController
{
public function indexAction(): string
{
return 'hello';
}
}
So then I went down the same path of trying to figure out the URL and I finally ended up here.
The actual controller URL
The method generateUrl, mentioned in the other answer is not present in any of my admin controllers for some reason. I looked and discovered it's defined in a Symfony trait. It essentially does this:
$this->container->get('router')->generate('my_route_name', [], UrlGeneratorInterface::ABSOLUTE_PATH);
Which finally returned the working URL:
/admin1/index.php/modules/my_project/my_path?_token=...
Hope this can help anyone else.

Laravel organize helper functions

Please, don't talk to technical in the answers:-D I am not a hardcore programmer.
What is a good way to store certain functions in Laravel? I have functions that apply on a "post" only or "media" only, like getAttributeList or getComponents. I say "Post" and "Media" because both have their own controller, model and views. It feels wrong to put it in the model because that should be database stuff right? And traits are more for recurring functions all over the place, right? So, right now I have one big file called Helpers.php. And uh, it is getting large... should I simply separate it in PostHelpers.php, MediaHelpers.php etc? Or is there a more elegant way in Laravel to do it?
It is quite simple : Just check your composer.json file at root directory of ur app. and under autoload section add :
"autoload": {
"psr-4": {
"App\\": "app/"
},
"files": ["app/helper.php"],
"classmap": [
"database/seeds",
"database/factories"
]
"files": ["app/helper.php"], This is the line you need to add in ur composer file and provide the path to file .
In my case i have created a file helper.php in App directory where i keep all my functions .
after this run this command :
composer dump-autoload
Now u can access your functions anywhere.
In your composer json file check this snippet
"autoload": {
"files": [
"app/Helpers/global_helper.php"
],
As you see I have auto loaded 1 single file called global_helper.php in a folder called Helpers Now in this file I have a function called loadHelper(...$files)
What this function does is
if (!function_exists('loadHelper')) {
function loadHelper(...$file_names)
{
foreach ($file_names as $file) {
include_once __DIR__ . '/' . $file . '_helper.php';
}
}
}
You can pass your file name as array or string and it will include those files into your Controller constructor
So In my Controller whenever I want some helper function I create a saperate helper file for that controller then in constructor i ust include it.
I am not sure if there is any better solution but so far this is how I am making all my projects .
I hope this will help you ;)

Not getting session data in custom helper file - Laravel 5.8

Actually, I am trying to define a constant and setting value from the session
in a custom helper added using Helper Service Provider. But not getting the session data in here.
I have added a Helper using Helper Service Provider, It's working fine.
But trying to get the session value.
In HelperServiceProvider.php
public function register()
{
foreach (glob(app_path().'/Helpers/*.php') as $filename){
require_once($filename);
}
}
And in ERPHelper.php in App/Helpers folder, I am trying to get the session data. But not getting the session value.
$company = session('company');
This is often down to the middleware. If you're setting the company session value under the web middleware, you might not be able to retrieve this is in a helper function registered by the service provider.
Also, out of interest, why are you setting this in a constant? It seems odd to me to use a the session helper to retrieve a value and then set it in a constant. A constant should probably not be used in this way but also you are adding an additional layer of abstraction. Why not just call session('company') as and when you need it?
I load in a helper Bootstrap.php via the composer.json file in the autoload section:
"autoload": {
"files": [
"app/Helpers/Bootstrap.php"
],
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database"
]
},
Then in the Bootstrap.php you could run your glob to load the relevant files.
That said, this still might not help because you're outside the web middleware. Can you not pass the session value to your helper function?
// Helper function.
function myErpHelper($companySessionValue) {
// My code here...
}
// Calling the helper function.
myErpHelper(session('company'));

How can I create a custom voyager Form Field from package?

I'm trying to create a repository composer package to create a custom form field for Voyager, and I found this example: https://github.com/bnku/extended-bread-form-fields , but this it doesn't work for me.
So, how do I build a custom field form for Voyager? The result would be this:
I tried this repository example.
https://github.com/bnku/extended-bread-form-fields (It didn't work for me)
and this is my repository test:
https://github.com/manuel90/crop-image-field
This is my composer.json of my package:
{
"name": "manuel90/crop-image-field",
"description": "New voyager form field to cut image when uploading",
"authors": [
{
"name": "Manuel",
"email": "testmlzra#gmail.com"
}
],
"require": {
"tcg/voyager": "^1.1"
},
"autoload": {
"psr-4": {
"Manuel90\\CropImageField\\": "src/"
}
},
"extra": {
"laravel": {
"providers": [
"Manuel90\\CropImageField\\CropImageFieldServiceProvider"
]
}
}
}
I can see these lines there's a trouble, it didn't detect the class "Voyager", but I don't know how to fix it:
if( class_exists('Voyager') ) {
Voyager::addFormField(CropImageFormField::class);
}
https://github.com/manuel90/crop-image-field/blob/master/src/CropImageFieldServiceProvider.php#L34-L36
( According docs this is the way to add a custom form Docs here )
I expect to see in the BREAD edit section the new custom field listed on the input type option, like this:
You need to move the Voyager::addFormField call to the boot() method as this counts as a "piece of functionality" which should be called after the voyager service providers are properly registered.
This is missing from Voyager's documentation because they only document the use case for adding FormFields at app level where the call from the register method runs after all vendor Service Providers are registered.

Laravel Route Group for Views

I have below configuration in my Laravel /routes/web.php:
Route::group(['prefix' => 'admin'], function(){
Route::get('/', function() {
return view('admin.login');
});
});
If you observe, I have mentioned view('admin.login') this calls /resources/views/admin/login.blade.php. Which holds good as of now.
But for this Route group, I will have all my views inside /resources/views/admin. Thus, I do not want to use admin before every view-name.
Is there any possible parameter at Route::group level by which I can define namespace of my views, so that the Laravel searches my views in the particular directory inside /resources/views/?
I faced the same problem and created a helper function it worked ...
added a helpers directory under app directory app\Helpers\functions.php
function adminView($file){
return view('foo.' . $file);
}
in composer.json file registered this file
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
},
"files": ["app/Helpers/functions.php"]
},
just run composer dump-autoload and you can use this helper function
You can use
View::addNamespace('admin', '/path/to/admin/views'); or View::addLocation('/path/to/your/admin/views');
to specify your admin view folder in your route file.
with the first method you can use
return view('admin::view.name'); and with the second method you can use view name directly like return view('view.name');

Categories