Installation Add the bundle via Composer:
composer require apisearch-io/apisearch-bundle
Register the bundle in config/bundles.php:
return [
// ...
Apisearch\Bundle\ApisearchBundle::class => ['all' => true],
];
Configuration Publish the default config:
php bin/console config:dump-reference apisearch
Configure config/packages/apisearch.yaml:
apisearch:
api_key: "%env(APISEARCH_API_KEY)%"
endpoint: "%env(APISEARCH_ENDPOINT)%"
project_id: "%env(APISEARCH_PROJECT_ID)%"
First Use Case Inject the client into a service/controller:
use Apisearch\Bundle\ApisearchBundle\Client\ApisearchClient;
class SearchController extends AbstractController
{
public function __construct(private ApisearchClient $client) {}
public function search(Request $request)
{
$query = $request->query->get('q');
$results = $this->client->search($query);
return $this->json($results);
}
}
Search Integration
ApisearchClient to execute queries:
$results = $this->client->search('query', [
'page' => 1,
'size' => 10,
'filters' => ['category' => 'electronics']
]);
nextPage() and prevPage() methods.Document Management
$this->client->index('products', [
'id' => '123',
'name' => 'Laptop',
'price' => 999.99
]);
$this->client->bulkIndex('products', [
['id' => '1', 'name' => 'Item 1'],
['id' => '2', 'name' => 'Item 2']
]);
Event-Driven Updates
ApisearchEvents (e.g., Indexed, Deleted) via Symfony’s event dispatcher:
$dispatcher->addListener(ApisearchEvents::INDEXED, function (IndexedEvent $event) {
// Log or process indexed documents
});
Symfony Forms
Use the bundle’s ApisearchType for search form fields:
use Apisearch\Bundle\ApisearchBundle\Form\Type\ApisearchType;
$builder->add('search', ApisearchType::class, [
'label' => 'Search',
'project_id' => 'your_project_id',
]);
Command-Line Tools
Leverage the ApisearchCommand for CLI operations:
php bin/console apisearch:index products data/products.json
Caching Cache search results using Symfony’s cache system:
$cacheKey = 'search_results_' . md5($query);
$results = $this->cache->get($cacheKey, function () use ($query) {
return $this->client->search($query);
});
API Key Management
APISEARCH_API_KEY is set in .env and not hardcoded.endpoint and project_id to avoid exposing secrets.Rate Limiting
429 errors and implement retries:
try {
$results = $this->client->search($query);
} catch (RateLimitExceededException $e) {
sleep(1); // Retry after delay
$results = $this->client->search($query);
}
BC Breaks
0.1.17, BC breaks in 0.2.0). Check the changelog for version-specific behaviors.UUID Handling
ramsey/uuid for document IDs. Ensure your documents include a valid UUID or handle conversion:
$document['id'] = (new Uuid())->toString();
Enable Debug Mode
Set debug: true in apisearch.yaml to log API requests/responses:
apisearch:
debug: true
Symfony Profiler
Use the ApisearchStopwatch to inspect search queries in the Symfony Profiler:
$this->client->search($query, ['stopwatch' => true]);
Error Handling Catch specific exceptions:
try {
$this->client->delete('products', '123');
} catch (DocumentNotFoundException $e) {
// Handle missing document
} catch (ApisearchException $e) {
// Generic error handling
}
Custom Clients
Extend ApisearchClient to add project-specific methods:
class CustomApisearchClient extends ApisearchClient
{
public function searchByCategory(string $category, int $limit = 10)
{
return $this->search('', [
'filters' => ['category' => $category],
'size' => $limit
]);
}
}
Event Subscribers
Create subscribers for ApisearchEvents to trigger actions (e.g., analytics, notifications):
class SearchAnalyticsSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
ApisearchEvents::SEARCH => 'onSearch',
];
}
public function onSearch(SearchEvent $event)
{
// Log search queries
}
}
Middleware Add custom middleware to the HTTP client for logging, auth, or request transformation:
$client = new ApisearchClient($config);
$client->getHttpClient()->setMiddleware([
new CustomMiddleware(),
]);
Testing
Use the ApisearchTestClient for unit tests:
$testClient = new ApisearchTestClient($this->createMock(ApisearchClient::class));
$results = $testClient->search('test');
$this->assertCount(2, $results);
Drift Integration
The bundle relies on drift/http-kernel for HTTP handling. Ensure compatibility if using Symfony 5+:
# config/packages/drift.yaml
drift:
http_kernel: true
Project ID Validation
The project_id must match the Apisearch project ID format (e.g., UUID). Validate early:
if (!Uuid::isValid($projectId)) {
throw new \InvalidArgumentException('Invalid project ID format');
}
Deprecated Methods
Some methods (e.g., ApisearchClient::query()) may be deprecated. Prefer search() for consistency.
How can I help you explore Laravel packages today?