Using the config file in Laravel Schedule Job - laravel

Can I load the config file when the scheduling job starts?
I tried to use a local variable customerName in Schedule Class and it already defined in the Config folder as named customerInfo.
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Config;
class Checkout extends Command
{
***
public function handle()
{
***
$customerName = Config::get('customerInfo.customer_name'); //test code
\Log::info($customerName); // for error check in log file
***
}
}
but it was not worked.
Do I have to declare it in the constructor
or have to use '\' as '\Config' even if already declared alias as use Config;?
What is the best simple solution to use custom variable in Config when schedule job is running start?

You are getting this error because you have not defined in what namespace PHP can find the Config class.
You need to either include the Config facade in your usings on top of the class:
use Config;
Or use the config helper function:
config('customerInfo.customer_name');

config() helper or Config Facade is used to get the values from config dir.
Create a new file in config folder with name customerInfo.
return [
'customer_name' => 'A name'
];
Now you can access the name
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class Checkout extends Command
{
***
public function handle()
{
***
$customerName = Config::get('customerInfo.customer_name'); //test code
\Log::info($customerName); // for error check in log file
***
}
}

Related

How to extend a laravel package within laravel 5.8 application?

I am new to Laravel and would appreciate any help on describing how a Laravel package residing in vendor folder can be extended and wont get affected if I update the package.
I'll try to create a brief guide, and we'll expand if need be.
I suggest putting all of your files inside a separate directory / namespace. You'll benefit from this should you decide to create your own composer package afterwards.
As an example I'll extend bumbummen99/shoppingcart package which forks the great gloudemans/shoppingcart, adding support for Laravel 5.8 and some minor functionality. You will of course first need to install that package:
composer require bumbummen99/shoppingcart
Start by making a couple of folders. You can use any name for folders / classes, this is what I used, relative to the project root:
app/Repositories/ExtendedCart
app/Repositories/ExtendedCart/Facades
Create the file
app/Repositories/ExtendedCart/ExtendedCart.php
This class will extend the package's main class:
namespace App\Repositories\ExtendedCart;
use Gloudemans\Shoppingcart\Cart;
class ExtendedCart extends Cart
{
public function myMethod(){
return 'myMethod';
}
}
Then make your Service Provider. Create the file:
app/Repositories/ExtendedCart/ExtendedCartServiceProvider.php
(I'm not using artisan as generating / moving the provider will produce wrong namespace)
This is your Service Provider content, here you reference the class that extends the package's class. Note you overwrite the binding from the original package.
namespace App\Repositories\ExtendedCart;
use Gloudemans\Shoppingcart\ShoppingcartServiceProvider;
class ExtendedCartServiceProvider extends ShoppingcartServiceProvider
{
public function register()
{
$this->app->bind('cart', 'App\Repositories\ExtendedCart\ExtendedCart');
}
}
Then register your service provider in config/app.php
'providers' => [
...
//Add this line to the end of providers array
App\Repositories\ExtendedCart\ExtendedCartServiceProvider::class,
]
Lastly create a Facade, which will instantiate the class (otherwise you will get non-static method exceptions). Create this file:
app/Repositories/ExtendedCart/Facades/ExtendedCart.php
This is the contents of the file:
namespace App\Repositories\ExtendedCart\Facades;
use Illuminate\Support\Facades\Facade;
class ExtendedCart extends Facade {
protected static function getFacadeAccessor() { return 'cart'; }
}
You're all set to use your extended methods. You can safely upgrade the original package, and you can even use the default facade:
namespace App\Http\Controllers;
use Cart;
class SomeController extends Controller{
public function someFunction(){
Cart::instance('default')->myMethod();
//This should return 'myMethod'
}
}
I hope this helps, good luck!

Laravel 5 how to include config file?

I am using Laravel 5.5 and I have a config file in dir app\Json\Schemas\TestSchema.php which contains an array with configurations like this:
return [
'value' => 'string'
];
What is the best way to include file dynamically?
In my model
namespace App;
use App\Json\Traits\JsonModel;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function getJsonSchema($schema)
{
return 'App\\Json\\Schemas\\'.$schema;
}
}
The best way would be to move your config file to the config folder. Lets assume you call it schema.php.
You can load the config file in your code using (where schema is the name of the config file without the .php):
config('schema');
And if you want the value, you can use dot notation (where schema is the name of the config file, and value is a key in the config array):
$value = config('schema.value');
Therefore the getJsonSchema function can be updated to (where $schema is the name of the config file):
public function getJsonSchema($schema)
{
return 'App\\Json\\Schemas\\'.config($schema.'.value');
}

Use custom folder(class) in controller

I created a new folder in the directory app which is called Services. So the directory of Services is app/Services. I want to use now a file of Services called Connection.php in a Controller app/Http/Controllers but when I try that, I get following error:
Class App\Services\Connection does not exist
I also tried to add the directory and file in my composer.json but this didn't fixed it either.
Controller:
namespace App\Services;
namespace App\Http\Controllers;
use App\Services\Connection;
use Illuminate\Http\Request;
class ExampleController extends Controller
{
protected $conn;
public function __construct(Connection $conn)
{
$this->conn = $conn;
}
Composer.json
"autoload": {
"classmap": [
"database",
"app/Services"
],
"autoload-dev": {
"classmap": [
"tests/TestCase.php",
"app/Services/Connection.php"
]
},
Edit 17.12.2016: (problem not solved yet)
Thanks for all who stick with me so long on this problem! I'm sry, if I gave too less information so I'll sum up few things that I tried.
1 => Deleted the secound namespace App\Services
2 => Added routes(or directory) to my composer.json ( like above )
3 => Used composer updated and composer dump-autoload
4 => Used use App\Services\Connection (the path to my connection class in Services, which I want to use in my ExampleController in App\Http\Controllers\ExampleController)
Connection class:
class Connection
{
//Some guzzle stuff
}
So the ExampleController looks exact as above just without the Services namespace anymore and I get exact the same error. What am I doing wrong?
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Contracts\Auth\Guard;
use App\Http\Controllers\Controller;
use App\Services\Connection;
class ExampleController extends Controller
{
public function __construct(Guard $auth, Connection $conn)
{
$this->auth = $auth;
$this->conn = $conn;
}
}
Please try to use this code.
Presented this solution as a comment but to make it easier for future viewers:
The solution to this is to ensure that proper name spacing is in all files being referenced including the controller and the classes. If the namespace isn't correct it won't be able to access it.
In this case you have to make sure that the namespace for the Connection class was using App\Services as the namespace and that the controller accessed it in the same namespace of App\Services\Connection.
The error is on your namespace declaration. you are declaring two namespaces for the same class!
namespace App\Services;
namespace App\Http\Controllers;
The last one will be used.
Remove the App\Http\Controllers namespace line.
Also remember that you should import the base controller:
use App\Controllers\Controller;
Why?
When you try to use App\Services\ExampleController, composer will look for that class in the autoload paths, but since your namespace is different, it will not be able to load it.

Setup VisualPHPUnit with Laravel

I'm using VisualPHPUnit as a GUI for my unit tests and I want to add it to my Laravel project.
I read this guide but it's obsolete being from 2015. There's no bootstrap.php file in config directory and there are no test_directories and bootstraps variables (I ran grep -rn . -e test_directories is Laravel directory).
Any idea what I can do to be able to add tests with artisan so they are working in VPU? Because Laravel test needs to extend Illuminate\Foundation\Testing\TestCase and VPU test needs to extend \PHPUnit_Framework_TestCase and I can't get it running. Either I don't see the test in VPU when I use Laravel's extend or I can't use Laravel's functions like visit when I use VPU's extend.
Edit:
Here's my PermissionTest.php:
<?php
namespace Visualphpunit\Test;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class PermissionTest extends \PHPUnit_Framework_TestCase
{
protected $baseUrl = 'http://localhost/laravel/public';
public function testExample()
{
$this->visit('/')->see('Logowanie');
}
public function createApplication()
{
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
return $app;
}
}
...for which I get this error: Fatal error: Class 'Visualphpunit\Test\Illuminate\Foundation\Testing\TestCase not found in .../laravel/VisualPHPUnit-master/tests/PermissionTest.php on line 10

How import custom class in controller Laravel?

I have created a new directory Library in root of Laravel.
Inside I put the file with class:
class My {
//
}
So, in controller Laravel I try to get access to this class:
App\Library\My
But Laravel does not determine this path.
This is my code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use View;
use App\Library\My;
class HomeController extends Controller
{
//
}
A complete and functional example based on the posts here:
1 - Folder and file - Create a folder under app/, in this example we will create a folder called Library.
We will also inside the folder create a file with the name of your class, here we will create a class called My.
So we will have app/Library/My.php
2 - Class and method - Now, for testing, inside the class create a static method called myMethod
<?php
namespace App\Library;
class My
{
public static function myMethod()
{
return 'it\'s work!';
}
}
3 - Controller - Now at the beginning of the Controller, we will declare the namespace of your Class with use:
<?php
namespace App\Http\Controllers;
use App\Library\My;
//rest of the controller code
Finally, to create an instance of the My class, in Controller, a new statement must be used:
//rest of the controller code
public function index()
{
$whatever = new My;
return $whatever::myMethod();
}
As above, make sure it is placed in the App directory and make sure it is properly namespaced e.g.
<?php
$fOne = new \App\library\functions;
$isOk = ($fOne->isOk());
?>
You should create Library folder inside app folder
namespace App\Library\My
app folder is alrdy used psr-4
In your controller
use App\Library\My as My
It's work for me. Hope this answer is helpful
You have to properly namespace your every class.
So you can import your class with use keyword, like so
use App\Library\My;
....
$my = new My();
Or if you've conflicting class name then you can use as keyword to alias the classname while importing
use App\Library\My as MySecond;
....
$my = new MySecond();
And if you want to directly access your class within the method then you can access it like so.
$my = new \App\Library\My();
Note: The leading \ means App was declared in the global scope.

Resources