1. Go to this page and download the library: Download silassare/php-utils library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
use PHPUtils\ClassUtils;
// Check if a class (or any parent/trait) uses a trait
ClassUtils::hasTrait(MyClass::class, SomeTrait::class); // bool
// Get all traits used transitively across the full class hierarchy
$traits = ClassUtils::getUsedTraitsDeep(MyClass::class);
// ['TraitFQCN' => 'TraitFQCN', ...]
use PHPUtils\FuncUtils;
function myHelper(): array {
return FuncUtils::getCallerLocation(); // ['file' => '...', 'line' => N]
}
// Returns the file and line of the code that called myHelper()
$location = myHelper();
use PHPUtils\PortablePattern;
PortablePattern::assertPortable('~^[a-z]+$~i'); // fine
PortablePattern::assertPortable('~^[a-z]++$~'); // InvalidArgumentException: a possessive quantifier is PCRE only
\preg_match(PortablePattern::toPcre('~^abc$~'), "abc\n"); // 0: as JavaScript answers
use PHPUtils\Env\EnvParser;
// From a file
$parser = EnvParser::fromFile('/path/to/.env');
// From a string
$parser = EnvParser::fromString("APP_ENV=production\nDEBUG=false");
// Get all values
$envs = $parser->getEnvs(); // ['APP_ENV' => 'production', 'DEBUG' => false]
// Get a single value
$env = $parser->getEnv('APP_ENV', 'local'); // 'production'
// Merge additional .env content
$parser->mergeFromFile('/path/to/.env.local');
$editor = $parser->edit();
// Update or append a key
$editor->upset('APP_ENV', 'staging');
$editor->upset('NEW_KEY', 'value', quote: true); // wraps in double-quotes
// Serialize back to string (preserves comments and whitespace)
$updated = (string) $editor;
file_put_contents('/path/to/.env', $updated);
use PHPUtils\Events\Event;
use PHPUtils\Events\EventManager;
use PHPUtils\Events\Interfaces\EventInterface;
// Define a custom event
class UserCreated extends Event {
public function __construct(public readonly int $userId) {}
}
// Register a listener (returns a detach closure)
$detach = UserCreated::listen(function (UserCreated $event) {
echo "User created: {$event->userId}";
});
// Dispatch the event
(new UserCreated(42))->dispatch();
// Detach the listener
$detach();
// Stop propagation
UserCreated::listen(function (UserCreated $event) {
$event->stopPropagation();
}, EventInterface::RUN_FIRST);
// Scoped channels
UserCreated::listen($handler, channel: 'admin');
(new UserCreated(42))->dispatch(channel: 'admin');
use PHPUtils\Exceptions\RuntimeException;
throw (new RuntimeException('Invalid configuration', ['key' => 'db.host']))
->suspect(['value' => $value, 'expected' => 'string'])
->suspectLocation(['file' => __FILE__, 'line' => __LINE__]);
// Retrieve exception data
$e->getData(); // hides keys starting with '_'
$e->getData(true); // shows all keys, including sensitive '_suspect'
use PHPUtils\FS\FSUtils;
$fs = new FSUtils('/var/www/project');
// Navigate
$fs->cd('public'); // change root
$fs->cd('cache', true); // change root, auto-create if missing
// Write / read
$fs->wf('config.json', json_encode($data));
$fs->append('log.txt', "New entry\n");
$fs->prepend('log.txt', "Header\n");
// Copy, move, delete
$fs->cp('src/', 'dist/');
$fs->rm('temp.txt');
$fs->rmdir('cache/');
// Create directories and symlinks
$fs->mkdir('uploads/avatars');
$fs->ln('../shared/assets', 'assets');
// Download a remote file
$fs->download('https://example.com/file.zip', 'downloads/file.zip');
// Walk a directory tree
$fs->walk('src/', function (string $file, string $path, bool $isDir) {
echo $path . PHP_EOL;
});
// File metadata
$info = $fs->info('uploads/');
$full = $fs->fullPathInfo('config.json');
use PHPUtils\FS\FSUtils;
$filter = (new FSUtils('/var/www/project'))->filter()
->isFile()
->name('/\.php$/')
->notPath('/vendor/')
->isReadable();
foreach ($filter->find() as $path => $fileInfo) {
echo $path . PHP_EOL;
}
// Assert conditions (throws RuntimeException on failure)
$filter->assert('/var/www/project/index.php');
// Check conditions (returns bool)
if (!$filter->check('/var/www/project/index.php')) {
echo $filter->getError();
}
use PHPUtils\Lock\Interfaces\LockableInterface;
use PHPUtils\Lock\Traits\LockableTrait;
class Config implements LockableInterface
{
use LockableTrait;
private array $data = [];
public function set(string $key, mixed $value): static
{
$this->assertNotLocked();
$this->data[$key] = $value;
return $this;
}
}
$config = new Config();
$config->set('debug', true);
$config->lock();
$config->isLocked(); // true
$config->set('debug', false); // throws RuntimeException
$config->unlock();
$config->isLocked(); // false
$config->set('debug', false); // OK
use PHPUtils\Lock\Interfaces\LockableInterface;
use PHPUtils\Lock\Traits\PermanentlyLockableTrait;
class FrozenConfig implements LockableInterface
{
use PermanentlyLockableTrait;
}
$config = new FrozenConfig();
$config->lock();
$config->unlock(); // throws RuntimeException — lock is permanent
use PHPUtils\Lock\Lock;
use PHPUtils\Lock\Interfaces\LockableInterface;
use PHPUtils\Lock\Interfaces\LockInterface;
use PHPUtils\Lock\Traits\LockableTrait;
$sharedLock = new Lock();
class TenantConfig implements LockableInterface
{
use LockableTrait;
public function __construct(private readonly LockInterface $token) {}
protected function createLock(): LockInterface { return $this->token; }
}
$a = new TenantConfig($sharedLock);
$b = new TenantConfig($sharedLock);
$a->lock();
$b->isLocked(); // true — same token
$a->unlock();
$b->isLocked(); // false — released via shared token
use PHPUtils\Interfaces\MetaCapableInterface;
use PHPUtils\Traits\MetaCapableTrait;
use PHPUtils\Store\Map;
class Product implements MetaCapableInterface
{
use MetaCapableTrait;
}
$product = new Product();
// Set individual keys
$product->setMetaKey('color', 'red');
$product->setMetaKey('weight', 1.5);
// Merge multiple keys at once (array or Map)
$product->mergeMeta(['origin' => 'France', 'certified' => true]);
// Read back
$product->getMeta()->get('color'); // 'red'
$product->getMeta()->toArray(); // ['color' => 'red', ...]
use PHPUtils\Traits\RecordableTrait;
class QueryBuilder {
use RecordableTrait;
}
$builder = new QueryBuilder();
$builder->where('id', 1)->orderBy('name'); // calls recorded
// Replay all calls on a real target
$realBuilder = new RealQueryBuilder();
$builder->play($realBuilder);
use PHPUtils\Store\Map;
$map = new Map();
$map->set('host', 'localhost');
$map->set('port', 5432);
$map->get('host'); // 'localhost'
$map->has('port'); // true
$map->toArray(); // ['host' => 'localhost', 'port' => 5432]
json_encode($map); // '{"host":"localhost","port":5432}'
json_encode(new Map()); // '{}'
// Accepts a reference to an existing array
$data = ['x' => 1];
$map = new Map($data);
$map->set('y', 2);
$data; // ['x' => 1, 'y' => 2] — reference is mutated
use PHPUtils\Store\Store;
$store = new Store(['user' => ['name' => 'Alice', 'roles' => ['admin']]]);
$store->get('user.name'); // "Alice"
$store->get('user.roles[0]'); // "admin"
$store->has('user.age'); // false
$store->set('user.age', 30);
$store->set("config['db.host']", 'localhost'); // bracket notation for keys with dots
$store->remove('user.roles[0]');
// ArrayAccess
$store['user.name'] = 'Bob';
echo $store['user.name']; // "Bob"
// Magic properties
$store->user; // same as $store->get('user')
// Deep merge — nested arrays/objects are merged recursively; type mismatch or leaf values are replaced
$store->merge(['user' => ['email' => '[email protected]']]);
// Dump to array
$store->toArray();
use PHPUtils\Store\StoreNotEditable;
$store = new StoreNotEditable($data);
$store->get('key'); // OK
$store->set('key', 'value'); // throws RuntimeException
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.