🧰 Stdlib - Useful basic tools library for PHP development.
Contains:
- array, string, number, object helper
- common php, OS env information
More Utils
PhpDotEnv
Dotenv(.env
) file loadAutoLoader
Simple autoloaderObjectBox
simple object containerOptional
like javajava.util.Optional
- and more ...
composer require toolkit/stdlib
use Toolkit\Stdlib\Str\StrBuffer;
$buf = StrBuffer::new("c");
$buf->prepend('ab')
$buf->append('de')
$str = (string)$buf; // "abcde"
$str = $buf->toString(); // "abcde"
// get and clean.
$str = $buf->fetch(); // "abcde"
$str = $buf->join(','); // "ab,c,de"
ObjectBox
- Simple object container.
use Toolkit\Stdlib\Obj\ObjectBox;
$box = ObjectBox::global();
// set
$box->set('router', function () {
return new MyRouter();
});
$box->set('renderer', [
'class' => MyRenderer::class,
'tplDir' => 'path/to/dir',
]);
// with options for create
$box->set('somObj', [
'class' => MyObject::class,
'__opt' => [
// will always create new object.
'objType' => ObjectBox::TYPE_PROTOTYPE,
],
]);
// get
/** @var MyRouter $router */
$router = $box->get('router');
/** @var MyRenderer $renderer */
$renderer = $box->get('renderer');
AutoLoader
- an simple psr4 loader, can use for tests.
AutoLoader::addFiles([
// alone files
]);
$loader = AutoLoader::getLoader();
$loader->addPsr4Map([
'namespace' => 'path'
]);
$loader->addClassMap([
'name' => 'class file'
]);
It aims to eliminate excessive if judgments.
Not use Optional:
use Toolkit\Stdlib\Util\Optional;
$userModel = UserModel::findOne(23);
if ($userModel) {
$username = $userModel->name;
} else {
$username = 'unknown';
}
Use Optional:
use Toolkit\Stdlib\Util\Optional;
$username = Optional::ofNullable($userModel)
->map(function ($userModel) {
return $userModel->name;
})->orElse('unknown');
Use arrow syntax:
use Toolkit\Stdlib\Util\Optional;
$username = Optional::ofNullable($userModel)
->map(fn($userModel) => $userModel->name)
->orElse('unknown');
PhpDotEnv
- a simple dont env file loader.
The env config file .env
(must is 'ini' format):
APP_ENV=dev
DEBUG=true
; ... ...
Usage:
PhpDotEnv::load(__DIR__, '.env');
env('DEBUG', false);
env('APP_ENV', 'prod');
use Toolkit\Stdlib\Util\Stream\DataStream;
use Toolkit\Stdlib\Util\Stream\ListStream;
$userList = ListStream::of($userModels)
->filter(fn($userModel) => $userModel->age > 20) // only need age > 20
->map(function ($userModel) {
// only need field: age, name
return [
'age' => $userModel->age,
'name' => $userModel->name,
];
})
->toArray();
vdump($userList);
$pf = PipeFilters::newWithDefaultFilters();
$val = $pf->applyString('inhere', 'upper'); // 'INHERE'
$val = $pf->applyString('inhere', 'upper|substr:0,3'); // 'INH'