Use Guzzle in Laravel package development - php

Recently i am working on a package for Laravel.
I am at beginner level on Laravel Package Development.
I need to use Guzzle Client for an API request from this package.
If i use use GuzzleHttp\Client; in my controller, it's showing class not found. (I know why. because it's outside of app folder and not autoloaded for this path)
Now, how can i use guzzle inside of my custom package controller.
Here what i wanting:
This is my controller method:
public function packageList($vendor, $type)
{
$client = new Client();
$result = $client->get('https://packagist.org/packages/list.json?vendor='.$vendor.'&type='.$type, [
'form_params' => [
'sample-form-data' => 'value'
]
]);
dd($result);
}
I attached classes of Guzzle
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
Getting Exception:
Class 'GuzzleHttp\Client' not found

Found this answer on stack with the same question
Open up your terminal at the root of your project and enter
composer require guzzlehttp/guzzle
It worked for the mailgun API. For some reason, the suggested method at the laravel's mail doc. You may install this package to your project by adding the following line to your composer.json file
"guzzlehttp/guzzle": "~5.3|~6.0"
doesn't make the composer download the Guzzle source codes. By the way, I didn't find out what | means in determining the version. This command just downloads the PSR code.
In this moment, the solution may work. However, be aware of compatibility issues. Because the command would install the latest stable version, not the suitable one.
answer by: shampoo
if this doesnt help, try reading the docs : http://docs.guzzlephp.org/en/stable/quickstart.html

Related

How to use Guzzle HTTP Client in simple PHP?

I am currently using PHP CURL but somehow it is not working for basicAUTH in my case. I want to use guzzel HTTP client in simple PHP project (not a Laravel project). Every solution on the internet I found is setting up in laravel and installing it via composer.
$client = new \GuzzleHttp\Client();
$response = $client->post($service_url, [
'auth' => [
$username,
$admin_password
]
]);
or if guzzel do not works with simple PHP, Suggest other client which can work with simple PHP for basic Auth. Thanks
First of all you need to navigate to your main forder you will be working in, which reside inside htdocs as usual and then insall GuzzleHttpClient by using composer tool
(Recommended: 2+ version)
composer require guzzlehttp/guzzle
It will download and install dependencies such as:
symfony/deprecation-contracts
psr/http-message
psr/http-client
guzzlehttp/promises
ralouphie/getallheaders, etc.
After getting it fully installed; try simple example to see if it really works
<?php
// First of all require autoload from vendor dir;
require_once "vendor/autoload.php";
use GuzzleHttp\Client;
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'https://reqres.in',
]);
// The response to get
$res = $client->request('GET', '/api/users', [
'query' => ['page' => '2', ]
]);
$body = $res->getBody();
$array_body = json_decode($body);
print_r($array_body);
?>
Check the result in the browser
Composer has nothing to do with Laravel or Guzzle, is "just" a package manager.
You can use - and I suggest to do so - composer in your project even if you're not using a framework.
Said that, once you have Guzzle source code (via composer or downloading directly the code; I would not reccommend the latter) you can just use it everywhere.
By the way I would suggest to use composer for two (main) reasons:
You can keep under control dependencies (like Guzzle) in order to update/downgrade them easily. Also composer will track possible conflicts with other dependencies (that for instance can't work together under some circumstances)
Composer has its own psr-4 autoloader
So yes, you can use Guzzle also without a framework and without composer, there's nothing preventing you to do so.

Cannot use Braintree package I've installed

I want to integrate Braintree php libary to my Laravel project (https://developers.braintreepayments.com/start/hello-server/php)
I've installed it with composer
require-dev{
"braintree/braintree_php" : "3.11.0"
}
But when I try to copy in the code such as I get this error in editor "Undefined class BrainTree_Configuration".
I've tried to require full path, put "\" before Braintree_Configuration: , "use" different paths
Braintree_Configuration::environment('sandbox');
It appears that both the Laravel and the Braintree docs are incorrect at the moment. In v 3.13.0 of the Braintree PHP package, the configuration class is \Braintree\Configuration, not \Braintree_Configuration.
I've just found this out and haven't completely tested it yet, but it looks like the only difference is the class name and namespace.
You can have a look at the current Configuration class on GitHub.
Also, if you're using Braintree with Laravel, it might help you to use their Cashier package, which will automatically include the Braintree package as well.
Just a note of warning, that the reference to the Braintree_Configuration class on this page is currently incorrect, as I mentioned above.

Laravel 5.2 - Class 'GuzzleHttp\Client' not found, on live server only

I have my config/mail 'driver' set to mandrill, host, port, etc. including in services.php mandrill secret set.
Sending Mail works fine locally, but on the live server I get:
Class 'GuzzleHttp\Client' not found
I have tried "guzzlehttp/guzzle": "~5.3|~6.0", and then back to "guzzlehttp/guzzle": "~4.0", no luck. I have done composer update, and dump-autoload still no luck on my live server. Been through every other associated Stackoverflow question and still can't resolve.
Please follow these simple steps:
First: Place this on top of your class
use Guzzlehttp\Client;
Second: Inside your function, instead of using
$client = new Client();
use
$client = new \GuzzleHttp\Client();
reference:
http://docs.guzzlephp.org/en/latest/quickstart.html
try composer require guzzlehttp/guzzle without specifying the version. Worked for me
Error ? the library GuzzleHttp (which is a Simple interface for building query strings, POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data ) is either missing or mis-configured.
Solution : run the following command on your terminal(root folder):
composer require guzzlehttp/guzzle:^6.5

Laravel: composer says it has installed library and updated composer.json but

but when I go to composer.json, the library ain't there showing.
I just wrote this:
php composer.phar require twilio/sdk
and I could see the typical running of dependencies and versions being installed
and I even updated it to make sure it had actually installed it (otherwise it would complain nothing ain't there) but
when I went to routes and wrote this:
Route::match(array('GET', 'POST'), '/sms', function()
{
$twiml = new Services_Twilio_Twiml();
$twiml->say('Hello - sorry to ring in the WC', array('voice' => 'alice'));
$response = Response::make($twiml, 200);
$response->header('Content-Type', 'text/xml');
return $response;
});
it says it can't find the class, so, either twilio is hiding from every predator or I don't know what.
Question:
So, eventually I would need to know the exact syntax to be added to the config app service providers but I can only find syntax for other libraries related to twilio which are not the official libraries for laravel and I d rather use twilio/sdk and not any other.
What would be the syntax for both the service provider and the alias façade?
Let's se.... And do you know what's the namespace? Because all you need in that case is at the top of the file:
use Path\To\Namespace\Class
and that's all... Or...
$twiml = New Path\To\Namespace\Services_Twilio_Twiml();

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