PHP code example of adrosoftware / laravel-data-proxy
1. Go to this page and download the library: Download adrosoftware/laravel-data-proxy 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/ */
adrosoftware / laravel-data-proxy example snippets
use AdroSoftware\DataProxy\DataProxy;
use AdroSoftware\DataProxy\Requirements;
use AdroSoftware\DataProxy\Shape;
use App\Models\User;
use App\Models\Post;
// Define all your data ape::make()
->select('id', 'name', 'email')
->with('profile')
->with('roles', Shape::make()->select('id', 'name'))
)
// Fetch their recent published posts
->query('posts', Post::class,
Shape::make()
->where('user_id', $userId)
->where('published', true)
->latest()
->limit(10)
->with('tags')
)
// Get aggregate counts
->count('totalPosts', Post::class,
Shape::make()->where('user_id', $userId)
)
// Compute derived values
->compute('stats', fn($data) => [
'posts' => $data['totalPosts'],
'hasProfile' => $data['user']?->profile !== null,
], dependsOn: ['user', 'totalPosts'])
);
// Access your data
echo $result->user->name;
echo $result->user->profile->bio;
foreach ($result->posts as $post) {
echo $post->title;
}
echo "Total posts: " . $result->totalPosts;
echo "Has profile: " . ($result->stats['hasProfile'] ? 'Yes' : 'No');
// Get performance metrics
$metrics = $result->metrics();
// ['queries' => 3, 'time_ms' => 12.5, 'memory_mb' => 2.1, 'batch_savings' => 2]
Requirements::make()
->one('user', User::class, $id) // Single entity by ID
->many('users', User::class, [1, 2, 3]) // Multiple entities by IDs
->query('posts', Post::class, $shape) // Query with constraints
->paginate('posts', Post::class, 15, 1) // Paginated query
->count('total', Post::class) // Count aggregate
->sum('views', Post::class, 'view_count') // Sum aggregate
->avg('rating', Post::class, 'rating') // Average aggregate
->min('oldest', Post::class, 'created_at') // Min aggregate
->max('newest', Post::class, 'created_at') // Max aggregate
->raw('custom', 'SELECT ...', $bindings) // Raw SQL
->compute('derived', $callback, $deps) // Computed value
->cache('user', 'user:1', ttl: 3600) // Cache configuration
Shape::make()
// Field selection
->select('id', 'title', 'content')
// Relations with nested shapes
->with('author')
->with('comments', Shape::make()
->select('id', 'post_id', 'body') // Include foreign key when selecting fields
->with('author')
->latest()
->limit(5)
)
// Constraints
->where('status', 'published')
->where('views', '>', 100)
->whereIn('category_id', [1, 2, 3])
->whereNull('deleted_at')
->whereHas('comments')
// Ordering and pagination
->orderBy('created_at', 'desc')
->latest() // Shorthand for orderBy('created_at', 'desc')
->limit(10)
->offset(20)
// Custom query scopes (accumulate - multiple calls are supported)
->scope(fn($query) => $query->withCount('likes'))
->scope(fn($query, $resolved) => $query->whereIn('author_id', $resolved['followedIds']))
// Output format
->asArray() // Return arrays instead of models
->present(PostPresenter::class) // Apply presenter
$result = DataProxy::make()->fetch(
Requirements::make()
->paginate('posts', Post::class, perPage: 15, page: 1,
shape: Shape::make()->where('published', true)->latest()
)
);
foreach ($result->posts as $post) {
echo $post->title;
}
echo "Page " . $result->posts->currentPage();
echo " of " . $result->posts->lastPage();
echo " - Total: " . $result->posts->total();
if ($result->posts->hasMorePages()) {
// Show next page link
}
$result = DataProxy::make()->fetch(
Requirements::make()
->query('categories', Category::class, Shape::make()->where('active', true))
->cache('categories', 'categories:active', ttl: 3600, tags: ['categories'])
);
// The categories query will be cached for 1 hour
// Invalidate with: Cache::tags(['categories'])->flush()
use AdroSoftware\DataProxy\Adapters\ClosurePresenterAdapter;
$adapter = new ClosurePresenterAdapter();
$adapter->register(User::class, function ($user) {
return new class($user) {
public function __construct(private $user) {}
public function __get($name) { return $this->user->{$name}; }
public function fullName(): string {
return $this->user->first_name . ' ' . $this->user->last_name;
}
};
});
$result = DataProxy::make()
->withPresenter($adapter)
->fetch($
use AdroSoftware\DataProxy\Adapters\LaravelModelPresenterAdapter;
$adapter = new LaravelModelPresenterAdapter(
namespace: 'App\\Presenters\\',
suffix: 'Presenter'
);
$result = DataProxy::make()
->withPresenter($adapter)
->fetch(
Requirements::make()
->one('user', User::class, 1,
Shape::make()->present(UserPresenter::class)
)
);
// Presenter methods available
echo $result->user->fullName();