zbateson/mb-wrapper
Lightweight PHP wrapper for mbstring that normalizes multibyte string operations across environments. Provides consistent encoding-aware helpers and safe fallbacks when mbstring isn’t available, making string handling more reliable in libraries and apps.
Install via Composer: composer require zbateson/mb-wrapper. Start by creating a MbWrapper instance—typically configured once per application (e.g., in a service provider) with the default encoding (usually 'UTF-8'):
use ZBateson\MbWrapper\MbWrapper;
$mb = new MbWrapper('UTF-8');
$length = $mb->strlen('-café'); // safely returns 4
For Laravel, bind it as a singleton in AppServiceProvider@register():
$this->app->singleton(\ZBateson\MbWrapper\MbWrapper::class, function ($app) {
return new MbWrapper(config('app.encoding', 'UTF-8'));
});
First use case: safely truncating user-generated content for display—e.g., mb->substr($text, 0, 50) avoids splitting multibyte characters.
MbWrapper into services/services handling user input, email subjects, or internationalized content—avoiding global mb_internal_encoding() calls.MbWrapper in trait classes (e.g., HasNormalizedTitle) to centralize and unit-test string logic:
public function getSafeTitleAttribute(): string
{
return $this->mb->substr($this->title, 0, 100) . '…';
}
config/app.php, enabling fallback handling (e.g., ISO-8859-1 for legacy integrations).$mb->strtolower($mb->trim($input)) or prefer chaining via the wrapper’s fluent interface where supported.MbWrapper is instantiated, its encoding can’t be changed—ensure it’s set correctly upfront. Re-instantiate if you need dynamic encoding.config('app.encoding') defaults to UTF-8—double-check it isn’t overridden elsewhere (e.g., in .env or middleware).mb_* functions are wrapped—e.g., mb_convert_encoding() isn’t included. Use native mb_convert_encoding() or extend MbWrapper if needed.logger()->info('MbWrapper initialized with encoding: ' . $mb->getEncoding());
MbWrapper to add app-specific operations (e.g., safeSlug() using mb_strtolower() and regex), keeping all multibyte calls centralized.mb_convert_encoding() before passing to the wrapper.How can I help you explore Laravel packages today?