Laravel using package [Requests for PHP] - php

I am using Laravel 6.5.2 and trying to use the package "Requests for PHP". https://requests.ryanmccue.info/download/
I installed this package using composer. The reason I want to use this packages is that I have all CRUD scripts created (using above package) and would like to reuse the scripts.
I suspect there might be some name conflict since Laravel comes installed with a HTTP request solution called Request, meanwhile the [PHP Request] has the same name.
Question:
Has anyone succesfully installed [Requests for PHP] package and got it to work with Laravel 6.X ?
Other findings:
Whe comment-out the autoloader line, the corresponding page prints "hello" as it should. Leaving this line active indicates in the laravel stack trace that the error is the line that holds the autoloader.
[Error]
Class 'App\Http\Controllers\Requests' not found
[routes/web.php]
Route::get("/requests", "Requests#read");
[app/Http/Controllers]
<?php
namespace App\Http\Controllers;
// use Illuminate\Http\Request; // Standard line, creeating a controller.
require_once '../vendor/rmccue/requests/library/Requests.php';
Requests::register_autoloader();
class Requests extends Controller {
public function read() {
echo "hello";
}
}

Related

PostHog namespace issue

I installed PostHog in my PHP codebase, and trying to use it by following the tutorial in this link (https://posthog.com/docs/integrate/server/php).
I am attempting to call PostHog::init function as a following:
PostHog::init($apikey,
array('host' => $baseUrl,
"debug" => true)
);
But I am getting error in this line PostHog::init, the error says
"Attempted to load class PostHog" from the global namespace. Did you forget a "use" statement?"
In fact, I am already using the "use" as following "use PostHog\PostHog;", but I am still getting this error. I can confrim that the Posthog library is intall becuase I can read the classess in Poshog library from my codebase.
This is more info about my app:
I use Symfony framework 5 and the app is deployed in docker. I use PHP 7.4 and posthog/posthog-php": "2.1.1".
I checked the vendor folder and PostHog is there (see photo attached)
I implemented service call PosthogHandler where I use PostHog functions (like init, capture and etc). I am calling functions' services from controller. But the issue is that the error appear in the PosthogHandler constructor in line PostHog::init, at PostHog initialisation stage. This is my PosthogHandler service class:
<?php
declare(strict_types=1);
namespace App\Posthogs;
use PostHog\PostHog;
use App\User\User;
class PosthogHandler
{
public function __construct($env, string $key, string $baseUrl)
{
PostHog::init($key,
array('host' => $baseUrl,
"debug" => true)
);
}
public function addEvent(string $eventName, User $user){
PostHog::capture(array(
'distinctId' => $user->getId()->id(),
'event' => $eventName
));
}
}
Any help, why I am getting above error?
The error indicates that your class file could not be autoloaded properly. You might want to check first that PostHog is present in vendor/autoload.php by creating a test file to check
<?php
require_once 'vendor/autoload.php';
var_dump(class_exists('Posthog\Posthog'));
If not you should try this command
composer dump-autoload
It works!
I have three vendor folders in (1) Frontend (1) Controller (3) Services.
Before, I only installed the PostHog library in services folder where I use PostHog functions. This didn't seem working despite the posthog lib appeared in vendor folder.
What it makes work and the error disappears when I installed the posthog lib in controller folder. I don't use posthog in controller at all, I am not sure why I need to install the posthog lib in controller folder in order to work. But eventually it works!

PHP error calling a function from a package

I am new to php and have just installed my first package via composer. I'm now trying to call a function from the package I installed as follows:
<?php
require_once 'vendor/autoload.php';
$value = 1;
$aws = AmazonGiftCode::make()->buyGiftCard($value);
echo $aws;
?>
But I get the following error:
PHP Fatal error: Uncaught Error: Class 'AmazonGiftCode' not found in
/public_html/php/test.php:4 Stack trace:
#0 {main} thrown in /public_html/php/test.php on line 4
Based on my (albeit limited) experience with other languages, I'm guessing I have to load the package that contains the class first. The package folder is in the same directory as the test.php file, in the subfolder vendor/kamerk22/AmazonGiftCode/. But I think this is where I don't know enough to troubleshoot it based on the information I could find.
Your directory structure should look like this.
test.php
composer.json
vendor
└───autoload.php
└───kamerk22
└───AmazonGiftCode
Make sure you installed the package using composer, and not by downloading it.
I'm guessing I have to load the package that contains the class first.
Unlike what you would normally expect when importing stuff, when using composer you only have to import the autoload.php file, and composer will take care of loading other packages as needed. By as needed what I mean is that as soon as composer sees you use the AmazonGiftCode class it will import the AmazonGiftCode package, but if one of your REST endpoints doesn't use anything from the AmazonGiftCode package it won't ever load it. This allows you to not have to worry about slowing down the entire application when you want to use a composer package for only a few endpoints. At least that's the way I understand how composer works.
Just run composer dump-autoload once and the class should known then.
You could also get verbose and use kamerk22\AmazonGiftCode\AmazonGiftCode;
But that AmazonGiftCode looks quite Laravel specific... that's why it may still fail, even if it may be found by auto-load. One needs to setup Laravel framework in the first place; just see this query (just in case if you may wonder where all these missing classes may come from).

Laravel 5.1 to 5.2 composer update error

Whenever I try to run composer update I now receive an error with a root cause of the following
Call to undefined method Illuminate\Bus\Dispatcher::mapUsing()
I can confirm Laravel 5.2 is properly installed, as are all other dependencies. This only happens when php artisan clear-compiled is run.
I've also updated my base controller based on a suggestion from a few hours ago in the Laracasts forum
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
abstract class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
But I still receive the error
UPDATE: This happens whenever the application is bootstrapped at all. My app won't even run now.
UPDATE 2, full stack trace:
PHP Fatal error: Call to undefined method Illuminate\Bus\Dispatcher::mapUsing() in /Users/Zara/Web/cafe/app/Providers/BusServiceProvider.php on line 16
PHP Stack trace:
PHP 1. {main}() /Users/Zara/Web/cafe/artisan:0
PHP 2. Illuminate\Foundation\Console\Kernel->handle() /Users/Zara/Web/cafe/artisan:36
PHP 3. Illuminate\Foundation\Console\Kernel->bootstrap() /Users/Zara/Web/cafe/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:105
PHP 4. Illuminate\Foundation\Application->bootstrapWith() /Users/Zara/Web/cafe/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:208
PHP 5. Illuminate\Foundation\Bootstrap\BootProviders->bootstrap() /Users/Zara/Web/cafe/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:203
PHP 6. Illuminate\Foundation\Application->boot() /Users/Zara/Web/cafe/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/BootProviders.php:17
PHP 7. array_walk() /Users/Zara/Web/cafe/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:718
PHP 8. Illuminate\Foundation\Application->Illuminate\Foundation\{closure}() /Users/Zara/Web/cafe/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:718
PHP 9. Illuminate\Foundation\Application->bootProvider() /Users/Zara/Web/cafe/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:717
PHP 10. Illuminate\Container\Container->call() /Users/Zara/Web/cafe/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:734
PHP 11. call_user_func_array:{/Users/Zara/Web/cafe/vendor/laravel/framework/src/Illuminate/Container/Container.php:507}() /Users/Zara/Web/cafe/vendor/laravel/framework/src/Illuminate/Container/Container.php:507
PHP 12. Cafe\Providers\BusServiceProvider->boot() /Users/Zara/Web/cafe/vendor/laravel/framework/src/Illuminate/Container/Container.php:507
[Symfony\Component\Debug\Exception\FatalErrorException]
Call to undefined method Illuminate\Bus\Dispatcher::mapUsing()
From the Laravel 5.2 Upgrade Guide
Separate Commands & Handlers
The Laravel 5.2 command bus now only supports self-handling commands and no longer supports separate commands and handlers.
If you would like to continue using separate commands and handlers, you may install a Laravel Collective package which provides backwards-compatible support for this: https://github.com/LaravelCollective/bus
There is no longer support for non self handling commands which is what the mapper would be for; mapping commands to handlers.
Check Service Providers
Check any service providers you have registered to make sure they aren't calling that method on dispatcher. If still having that issue, you can try checking any package service providers to make sure they aren't calling that method.

PhantomJs cannot execute binary file

I am trying to use PhantomJs in my laravel 5 project. I have downloaded via composer. I have added into my providers section and aliases section within config/app.php
Okay so i have now created my controller as seen below:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use PDF;
use View;
class PdfController extends Controller {
public function index()
{
$view = View::make('home');
return PDF::createFromView($view, 'home.pdf');
}
}
I have also created my route for this method. However when i try this in my browser it throws the following error:
PhantomJS: sh: /Users/matts/sites/ManagementApp/vendor/antking/phantom-pdf/src/../bin/phantomjs: cannot execute binary file
Has anyone come across this before?
Thanks
The "cannot execute binary file" indicates that it was not able to run phantomjs at all, and it is probably not related to your code. The most likely reason for this is an architecture incompatibility. Depending on whether or not you have a 32 or 64 bit system, you should use either phantomjs-1.9.8-linux-x86_64 (64bit) or phantomjs-1.9.8-linux-i686. It is possible that you used the wrong one for your system.

Creating a new ServiceProvider / Facade as a package in Laravel 5

Introduction
I've never worked with a framework before (Zend, CakePHP, etc) and finally decided to sit down and learn one. I'm starting with Laravel because the code looks pretty and unlike some other frameworks I tried to install, the "Hello, World!" example worked on the first try.
The Goal
For the time being, I want my app to do something very simple:
User submits a request in the form of: GET /dist/lat,lng
The app uses the remote IP address and MaxMind to determine $latitude1 and $longitude1
This request path is parsed for $latitude2 and $longitude2
Using these two positions, we calculate the distance between them. To do this I'm using Rafael Fragoso's WorldDistance PHP class
Since I plan to re-use this function in later projects, it didn't seem right to throw all of the code into the /app directory. The two reusable parts of the application were:
A service provider that connects to MaxMind and returns a latitude and longitude
A service provider that takes two points on a globe and returns the distance
If I build facades correctly then instead of my routes.php file being a mess of closures within closures, I can simply write:
Route::get('dist/{input}', function($input){
$input = explode( "," , $input );
return Distance::getDistance( GeoIP::getLocation(), $input );
});
What I've tried
Initial Attempt
For the first service provider, I found Daniel Stainback's Laravel 5 GeoIP service provider. It didn't install as easily as it should have (I had to manually copy geoip.php to the /config directory, update /config/app.php by hand, and run composer update and php artisan optimize) however it worked: A request to GET /test returned all of my information.
For the second service provider, I started by trying to mimic the directory structure and file naming convention of the GeoIP service provider. I figured that if I had the same naming convention, the autoloader would be able to locate my class. So I created /vendor/stevendesu/worlddistance/src/Stevendesu/WorldDistance\WorldDistanceServiceProvider.php:
<?php namespace Stevendesu\WorldDistance;
use Illuminate\Support\ServiceProvider;
class WorldDistanceServiceProvider extends ServiceProvider {
protected $defer = false;
public function register()
{
// Register providers.
$this->app['distance'] = $this->app->share(function($app)
{
return new WorldDistance();
});
}
public function provides()
{
return ['distance'];
}
}
I then added this to my /config/app.php:
'Stevendesu\WorldDistance\WorldDistanceServiceProvider',
This fails with a fatal error:
FatalErrorException in ProviderRepository.php line 150:
Class 'Stevendesu\WorldDistance\WorldDistanceServiceProvider' not found
Using WorkBench
Since this utterly failed I figured that there must be some other file dependency: maybe without composer.json or without a README it gives up. I don't know. So I started to look into package creation. Several Google searches for "create package laravel 5" proved fruitless. Either:
They were using Laravel 4.2, in which case the advice was "run php artisan workbench vendor/package --resources"
Or
They were using Laravel 5, in which case the docs were completely useless
The official Laravel 5 docs give you plenty of sample code, saying things like:
All you need to do is tell Laravel where the views for a given namespace are located. For example, if your package is named "courier", you might add the following to your service provider's boot method:
public function boot()
{
$this->loadViewsFrom(__DIR__.'/path/to/views', 'courier');
}
This makes the assumption that you have a service provider to put a boot method in
Nothing in the docs says how to create a service provider in such a way that it will actually be loaded by Laravel.
I also found several different resources all of which assume you have a repository and you just want to include it in your app, or assume you have "workbench". Nothing about creating a new package entirely from scratch.
PHP Artisan did not even have a "workbench" command, and there was no "workbench.php" file in /config, so anything I found related to workbench was worthless. I started doing some research on Workbench and found several different questions on StackOverflow.
After a long time and some experimentation, I managed to get laravel/workbench into my composer.json, composer update, composer install, manually build a workbench.php config file, and finally use the PHP Artisan Workbench command to make a new package:
php artisan workbench Stevendesu/WorldDistance --resources
This created a directory: /workbench/stevendesu/world-distance with a number of sub-directories and only one file: /workbench/stevendesu/world-distance/src/Stevendesu/WorldDistance/WorldDistanceServiceProvider.php
This service provider class looked essentially identical to the file I created before, except that it was in the /workbench directory instead of the /vendor directory. I tried reloading the page and I still got the fatal error:
FatalErrorException in ProviderRepository.php line 150:
Class 'Stevendesu\WorldDistance\WorldDistanceServiceProvider' not found
I also tried php artisan vendor:publish. I don't really know what this command does and the description wasn't helpful, so maybe it would help? It didn't.
Question
How do I create a new service provider as a package so that in future projects I can simply include this package and have all the same functionality? Or rather, what did I do wrong so that the package I created isn't working?
After two days of playing with this I managed to find the solution. I had assumed that the directory structure mapped directly to the autoloader's path that it checked (e.g. attempting to access a class Stevendesu\WorldDistance\WorldDistanceServiceProvider would look in vendor/stevendesu/world-distance/WorldDistanceServiceProvider)... This isn't the case.
Reading through the composer source code to see how it actually loads the files, it builds a "classmap" - essentially a gigantic array mapping classes to their respective files. This file is built when you run composer update or composer install - and it will only be built correctly if composer knows the details of your package. That is - if your package is included in your project's composer.json file
I created a local git repository outside of my app then added my package to my app's composer.json file then ran composer update -- suddenly everything worked perfectly.
As for the:
It didn't install as easily as it should have
the secret sauce here was first add the service provider to /config/app.php then, second run php artisan vendor:publish

Categories