Skip to content

Instantly share code, notes, and snippets.

@oliuz
Forked from hersan/ReportFactory
Created March 27, 2021 02:09
Show Gist options
  • Select an option

  • Save oliuz/bff7992cd903ec0a2f6ab441ab5b33de to your computer and use it in GitHub Desktop.

Select an option

Save oliuz/bff7992cd903ec0a2f6ab441ab5b33de to your computer and use it in GitHub Desktop.
Ejemplo de implementación del Patrón Factory
<?php
//Esto lo agregas en el AppServiceProvider, de esta forma puedes inyectar la clase donde lo necesites
$this->app->bind(ReportFactory::class, function($app) {
$config = $app['config']->get('report-factory');
return new ReportFactory($app, $config['report_type']);
});
<?php
return [
'report_type' => [
'dompdf' => 'dompdf.wrapper',
'snappy' => 'snappy.pdf.wrapper',
]
];
<?php
namespace App\Services;
use Illuminate\Foundation\Application;
class ReportFactory
{
private $app;
private $config;
public function __construct(Application $app, array $config)
{
$this->app = $app;
$this->config = $config;
}
public function create(String $reportType)
{
$drive = $this->resolveDrive($reportType);
if (!$this->app->bound($drive)) {
throw new \InvalidArgumentException("The pdf report type: {$drive} is not installed");
};
return $this->app->make($drive);
}
public static function new(Application $app, array $config)
{
return new static($app, $config);
}
public function resolveDrive($drive)
{
if (!array_key_exists($drive, $this->config)) {
throw new \InvalidArgumentException("The pdf report type: {$drive} is not valid");
}
return $this->config[$drive];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment