composer require bitandblack/hyphenizer-sdk-php
use BitAndBlack\HyphenizerSdk\Client;
use BitAndBlack\HyphenizerSdk\Config;
$config = new Config('YOUR_API_KEY');
$client = new Client($config);
$result = $client->hyphenate('Laravel', 'en');
echo $result->getHyphenatedText(); // Output: "La-ra-vel"
src/ directory for class methods.Config class for API key, endpoint, and timeout settings.HyphenationResult methods like getHyphenatedText(), getLanguage(), and getStatus().Batch Hyphenation:
$texts = ['Laravel', 'Eloquent', 'Blade'];
$language = 'en';
foreach ($texts as $text) {
$result = $client->hyphenate($text, $language);
// Process result (e.g., store in DB, render in view)
}
Language Detection:
Use a library like mobiledetectlib/mobile-detect to auto-detect language and pass it to the hyphenator:
$detect = new MobileDetect;
$language = $detect->getLanguage() ?: 'en'; // Fallback to English
$result = $client->hyphenate($userInput, $language);
Integration with Blade Views: Create a custom Blade directive or helper:
// app/Helpers/Hyphenator.php
use BitAndBlack\HyphenizerSdk\Client;
use BitAndBlack\HyphenizerSdk\Config;
function hyphenate($text, $language = 'en') {
static $client = new Client(new Config(config('services.hyphenizer.api_key')));
return $client->hyphenate($text, $language)->getHyphenatedText();
}
Usage in Blade:
<p>{{ hyphenate('Laravel', 'en') }}</p>
Caching Responses: Cache hyphenated results to reduce API calls (e.g., using Laravel's cache):
$cacheKey = "hyphenated:{$text}:{$language}";
$hyphenatedText = cache()->remember($cacheKey, now()->addHours(1), function() use ($client, $text, $language) {
return $client->hyphenate($text, $language)->getHyphenatedText();
});
Environment Configuration:
Store the API key in .env:
HYPHENIZER_API_KEY=your_api_key_here
Load it in config/services.php:
'hyphenizer' => [
'api_key' => env('HYPHENIZER_API_KEY'),
],
Then inject the config into the Client:
$client = new Client(new Config(config('services.hyphenizer.api_key')));
Error Handling:
Wrap API calls in try-catch blocks to handle exceptions (e.g., BitAndBlack\HyphenizerSdk\Exception\HyphenizerException):
try {
$result = $client->hyphenate($text, $language);
} catch (\Exception $e) {
Log::error("Hyphenation failed: " . $e->getMessage());
return $text; // Fallback to original text
}
Rate Limiting: Implement a queue (e.g., Laravel Queues) for bulk hyphenation to avoid hitting API limits:
// Dispatch a job for each text
HyphenateJob::dispatch($text, $language);
API Key Leaks:
.env from version control (add it to .gitignore).Language Support:
und for Undetermined) and handle unsupported languages gracefully:
$supportedLanguages = ['en', 'de', 'fr']; // Example
if (!in_array($language, $supportedLanguages)) {
$language = 'en'; // Default fallback
}
Text Length Limits:
if (strlen($text) > 1000) {
throw new \InvalidArgumentException("Text too long for hyphenation.");
}
Rate Limits:
X-RateLimit-* fields. Implement exponential backoff for retries:
use Symfony\Component\HttpClient\Retry\RetryStrategy;
$client = new Client($config, [
'http_client' => HttpClient::create([
'base_uri' => 'https://api.bitandblack.com',
'retry' => RetryStrategy::create(
RetryStrategy::MAX_RETRIES,
RetryStrategy::PURE_RETRY,
null,
null,
null,
100 // Initial delay in ms
),
]),
]);
Case Sensitivity:
$normalizedText = mb_strtolower($text);
Enable Verbose Logging: Configure the HTTP client to log requests/responses:
$client = new Client($config, [
'http_client' => HttpClient::create([
'headers' => [
'Accept' => 'application/json',
],
'event_dispatcher' => new EventDispatcher(),
'logger' => new StreamHandler(storage_path('logs/hyphenizer.log'), Logger::DEBUG),
]),
]);
Inspect Raw Responses: Access the raw response object for debugging:
$result = $client->hyphenate($text, $language);
\Log::debug('Raw response:', [$result->getRawResponse()->getContent(false)]);
Mock the Client for Testing:
Use Laravel's MockHttpClient to simulate API responses in tests:
use Symfony\Component\HttpClient\MockHttpClient;
$mockClient = new MockHttpClient([
new MockResponse('{"hyphenatedText":"La-ra-vel"}', ['http_code' => 200]),
]);
$client = new Client($config, ['http_client' => $mockClient]);
Custom Response Handlers:
Extend the HyphenationResult class to add domain-specific methods:
class CustomHyphenationResult extends HyphenationResult {
public function isValid(): bool {
return $this->getStatus() === 'success';
}
public function getHyphenatedWords(): array {
return explode('-', $this->getHyphenatedText());
}
}
Override the client's response factory to return your custom class.
Add Retry Logic: Implement custom retry logic for specific HTTP status codes (e.g., 429 Too Many Requests):
$client = new Client($config, [
'http_client' => HttpClient::create([
'on_options' => function (Options $options) {
$options->setRetry(5, 100, function ($result, $retry, $options) {
return $result->getStatusCode() >= 500 || $result->getStatusCode() === 429;
});
},
]),
]);
Language Fallback Chain: Create a fallback chain for unsupported languages:
$fallbackLanguages = ['en', 'de', 'fr'];
$language = $this->resolveLanguage($request->language, $fallbackLanguages);
private function resolveLanguage(?string $language, array $fallbacks): string {
return in_array($language, $fallbacks) ? $language : $fallbacks[0];
}
Batch Processing Middleware: Add middleware to the HTTP client to log or transform requests/responses:
$client = new Client($config, [
'http_client' => HttpClient::create([
'on_options' => function (
How can I help you explore Laravel packages today?