Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Create Client Bundle Laravel Package

aurelien/create-client-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require aurelien/create-client-bundle
    
    • Verify the package is autoloaded by checking vendor/composer/autoload_psr4.php for the namespace Aurelien\CreateClientBundle.
  2. Basic Usage

    • Register the bundle in config/app.php under providers:
      Aurelien\CreateClientBundle\CreateClientBundleServiceProvider::class,
      
    • Publish the config (if available) with:
      php artisan vendor:publish --provider="Aurelien\CreateClientBundle\CreateClientBundleServiceProvider" --tag="config"
      
    • Check config/create-client-bundle.php for default settings (if published).
  3. First Use Case: Generating a Client Class

    • Use the artisan command to scaffold a client:
      php artisan create:client --name=MyApiClient --base-url=https://api.example.com
      
    • This generates a new client class in app/Clients/MyApiClient.php with basic HTTP methods (e.g., get(), post()).

Implementation Patterns

Workflows

  1. Client Generation

    • Dynamic Clients: Use the --name and --base-url flags to generate clients for different APIs:
      php artisan create:client --name=StripeClient --base-url=https://api.stripe.com
      
    • Custom Headers: Extend the generated client by overriding the getHeaders() method:
      class StripeClient extends BaseClient {
          protected function getHeaders(): array {
              return array_merge(parent::getHeaders(), [
                  'Authorization' => 'Bearer ' . config('services.stripe.key'),
              ]);
          }
      }
      
  2. Integration with Laravel Services

    • Bind the generated client to the container in a service provider:
      $this->app->singleton(MyApiClient::class, function ($app) {
          return new MyApiClient(config('services.my_api.url'));
      });
      
    • Inject the client into controllers/services:
      public function __construct(private MyApiClient $client) {}
      
  3. API Request Handling

    • Use the client’s methods in controllers:
      public function fetchData() {
          $response = $this->client->get('/endpoint');
          return response()->json($response->data);
      }
      
    • Handle responses with Laravel’s Http facade or custom logic:
      $data = json_decode($response->body, true);
      
  4. Testing

    • Mock the client in tests using Laravel’s mocking tools:
      $this->mock(MyApiClient::class, function ($mock) {
          $mock->shouldReceive('get')->andReturn((object) ['data' => []]);
      });
      

Integration Tips

  • Configuration Management: Store API URLs and keys in .env and bind them to config:
    MY_API_URL=https://api.example.com
    
    'url' => env('MY_API_URL'),
    
  • Error Handling: Extend the client to throw custom exceptions:
    class MyApiClient extends BaseClient {
        protected function handleResponse($response) {
            if ($response->status !== 200) {
                throw new ApiException($response->body);
            }
            return json_decode($response->body, true);
        }
    }
    
  • Logging: Add logging for API calls:
    protected function logRequest($method, $url, $data) {
        \Log::info("API Call: {$method} {$url}", ['data' => $data]);
    }
    

Gotchas and Tips

Pitfalls

  1. Namespace Conflicts

    • Ensure the generated client’s namespace (app/Clients/) doesn’t clash with existing classes. Customize the output path in the artisan command if needed (check the package’s source for extension points).
  2. Missing Dependencies

    • The package requires PHP 7.x but may lack explicit dependencies (e.g., guzzlehttp/guzzle). Add it manually if HTTP requests fail:
      composer require guzzlehttp/guzzle
      
  3. Config Publishing

    • If the package doesn’t publish a config file, default values may be hardcoded. Override the service provider’s register() method to customize behavior:
      $this->app->singleton('client', function () {
          return new MyApiClient(config('custom.api_url'));
      });
      
  4. Artisan Command Issues

    • If the command fails, verify:
      • The command is registered in app/Console/Kernel.php.
      • The package’s service provider is loaded.

Debugging

  • Check Generated Files: Inspect app/Clients/ for the generated client class. If empty, the artisan command may not be working.
  • Enable Debug Mode: Set APP_DEBUG=true in .env to see detailed errors.
  • Log HTTP Requests: Use Guzzle’s middleware to log requests:
    $client = new MyApiClient();
    $client->getClient()->getEmitter()->attach(
        new \GuzzleHttp\Middleware::tap(function ($request) {
            \Log::debug('Request:', [
                'url' => (string) $request->getUri(),
                'method' => $request->getMethod(),
            ]);
        })
    );
    

Tips

  1. Extend Base Client

    • Override methods in the generated client to add retries, timeouts, or middleware:
      protected function getClient() {
          return new \GuzzleHttp\Client([
              'timeout' => 30,
              'headers' => $this->getHeaders(),
          ]);
      }
      
  2. Use Traits for Reusability

    • Create a trait for common API logic (e.g., pagination, rate limiting):
      trait ApiClientTrait {
          protected function paginate($url, $perPage = 20) {
              $response = $this->get("{$url}?per_page={$perPage}");
              return $response->data;
          }
      }
      
  3. Document Clients

    • Add PHPDoc blocks to generated clients for IDE autocompletion:
      /**
       * Fetches user data from the API.
       *
       * @param int $id User ID
       * @return array User data
       */
      public function getUser($id) { ... }
      
  4. Leverage Laravel Mixins

    • Use Laravel’s mixin feature to add methods to the client dynamically:
      \Illuminate\Support\Facades\Blade::mixin(function () {
          // Add custom Blade directives for API responses
      });
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui