Skip to content

Instantly share code, notes, and snippets.

@adamgoose
Last active April 26, 2016 22:34
Show Gist options
  • Save adamgoose/3f6a9de6207791640b6c04b9f0f08ef7 to your computer and use it in GitHub Desktop.
Save adamgoose/3f6a9de6207791640b6c04b9f0f08ef7 to your computer and use it in GitHub Desktop.
IoC Container Tutorail
<?php namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Facades\Textify;
class ApiController extends Controller {
public function postSendSms(Request $request, Textify $textify) {
$this->validate($request, [
'number' => 'required',
'text' => 'required'
]);
$itWorked = $textify->send($request->text, $request->number);
// return whatever
}
}
<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Services\Textify;
class AppServiceProvider extends ServiceProvider {
public function boot() {}
public function register() {
$this->app->singleton(Textify::class, function() {
return new Textify(config('services.textify.url'));
});
$this->app->alias(Textify::class, 'textify');
}
}
<?php namespace App\Services;
use GuzzleHttp\Client;
class Textify {
/**
* @var string $host
*/
protected $host;
/**
* @var Client
*/
protected $client;
/**
* @param string $host
*/
public function __construct($host)
{
$this->host = $host;
$this->prepareGuzzleClient();
}
/**
* @param string $text
* @param string $number
*/
public function send($text, $number)
{
$response = $this->client->post('/api/sms', [
'json' => compact('text', 'number'),
]);
return $this->respond($response);
}
/**
* @param Response $response
*
* @return bool|array
*/
protected function respond($response)
{
if($response->getStatusCode() >= 400) {
return false;
}
return json_decode($response->getBody(), true);
}
/**
* @return void
*/
protected function prepareGuzzleClient()
{
$this->client = new Client([
'base_uri' => $this->host,
'exceptions' => false,
]);
}
}
<?php namespace App\Facades;
use Illuminate\Support\Facade;
class Textify extends Facade {
protected function getFacadeAccesor() {
return 'textify';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment