Is laravel-data Laravel dependent? #633
-
Is it possible to use this package in a non-Laravel project, for example in Slim framework? (Of course, I see the name of the package, but I don't see any huge dependency in composer.json) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
It's possible but not very easy. It doesn't have many dependencies but it implicitly depends on a global I was able to make a small proof of concept only using laravel-data and the container package: The global helpers (copied from a laravel project): <?php
use Illuminate\Container\Container;
function app($abstract = null, array $parameters = [])
{
if (is_null($abstract)) {
return Container::getInstance();
}
return Container::getInstance()->make($abstract, $parameters);
}
function config($key = null, $default = null)
{
if (is_null($key)) {
return app('config');
}
if (is_array($key)) {
return app('config')->set($key);
}
return app('config')->get($key, $default);
} For the config I made a small class but you'll need the full package for configuring laravel-data since it deals with nested arrays: class Config
{
public function __construct(public array $config = []) {}
public function get(string $key, mixed $default = null): mixed
{
return $this->config[$key] ?? $default;
}
public function set(array|string $key, mixed $value = null)
{
if (is_array($key)) {
foreach ($key as $_key => $_value) {
$this->config[$_key] = $_value;
}
} else {
$this->config[$key] = $value;
}
}
} The Test data class: use Spatie\LaravelData\Data;
class Foo extends Data
{
public function __construct(
public string $title = 't',
public string $slug = 's',
) {}
} The container configuration: use Spatie\LaravelData\Support\DataConfig;
app()->singleton('config', function () {
return new Config([
'data.normalizers' => [
\Spatie\LaravelData\Normalizers\ModelNormalizer::class,
\Spatie\LaravelData\Normalizers\ArrayableNormalizer::class,
\Spatie\LaravelData\Normalizers\ObjectNormalizer::class,
\Spatie\LaravelData\Normalizers\ArrayNormalizer::class,
\Spatie\LaravelData\Normalizers\JsonNormalizer::class,
]
]);
});
app()->singleton(DataConfig::class, fn () => new DataConfig([])); And finally the test itself: <?php
$foo = Foo::from(['title' => '123', 'slug' => '456']);
var_dump($foo->title); // "123"
var_dump($foo->slug); // "456" I didn't try anything more complex so you'll probably need to tinker with it to get it to work well. |
Beta Was this translation helpful? Give feedback.
It's possible but not very easy. It doesn't have many dependencies but it implicitly depends on a global
app
function which returns a laravel container (packageilluminate/container
) and a globalconfig
function that returns a config object (packageilluminate/config
) or classes that have similar functions (since it doesn't check for an interface).I was able to make a small proof of concept only using laravel-data and the container package:
The global helpers (copied from a laravel project):