PHP code example of nette / assets

1. Go to this page and download the library: Download nette/assets 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/ */

    

nette / assets example snippets


public function __construct(
	private Nette\Assets\Registry $assets
) {}

public function renderDefault(): void
{
	$logo = $this->assets->getAsset('images/logo.png');
	$this->template->logo = $logo;
}

$image = $assets->getAsset('photo.jpg');
echo $image->url;    // '/assets/photo.jpg?v=1699123456'
echo $image->width;  // 800
echo $image->height; // 600

// Inject the registry
public function __construct(
	private Nette\Assets\Registry $assets
) {}

// Use it to get assets
$logo = $this->assets->getAsset('images/logo.png');

// Uses the 'default' mapper
$css = $assets->getAsset('style.css');

// Uses the 'images' mapper (using prefix)
$photo = $assets->getAsset('images:photo.jpg');

// Uses the 'images' mapper (using array)
$photo = $assets->getAsset(['images', 'photo.jpg']);

use Nette\Assets\Registry;
use Nette\Assets\FilesystemMapper;

// Create registry
$registry = new Registry;

// Add mappers manually
$registry->addMapper('default', new FilesystemMapper(
	baseUrl: 'https://example.com/assets',   // URL prefix
	basePath: __DIR__ . '/assets',           // Filesystem path
	extensions: ['webp', 'jpg', 'png'],      // Try WebP first, fallback to JPG/PNG
	versioning: true
));

// Use the registry
$logo = $registry->getAsset('logo');  // Finds logo.webp, logo.jpg, or logo.png
echo $logo->url;

// This throws Nette\Assets\AssetNotFoundException if file doesn't exist
try {
	$logo = $assets->getAsset('images/logo.png');
	echo $logo->url;
} catch (AssetNotFoundException $e) {
	// Handle missing asset
}

// This returns null if file doesn't exist
$banner = $assets->tryGetAsset('images/banner.jpg');
if ($banner) {
	echo $banner->url;
}

// Use default mapper
$asset = $assets->getAsset('document.pdf');

// Use specific mapper using prefix with colon
$asset = $assets->getAsset('images:logo.png');

// Use specific mapper using array syntax
$asset = $assets->getAsset(['images', 'logo.png']);

// Images
$image = $assets->getAsset('photo.jpg');
echo $image->width;   // 1920
echo $image->height;  // 1080
echo $image->url;     // '/assets/photo.jpg?v=1699123456'

// All assets can be cast to string (returns URL)
$url = (string) $assets->getAsset('document.pdf');

$image = $assets->getAsset('photo.jpg');
// No file operations yet

echo $image->url;    // Just returns URL, no file reading

echo $image->width;  // NOW it reads the file header to get dimensions
echo $image->height; // Already loaded, no additional file reading

// For MP3 files, duration is estimated (most accurate for Constant Bitrate files)
$audio = asset('audio:episode-01.mp3');
echo $audio->duration; // in seconds

// Even generic assets lazy-load their MIME type
$file = $assets->getAsset('document.pdf');
echo $file->mimeType; // Now it detects: 'application/pdf'

// Disable versioning for specific asset
$asset = $assets->getAsset('style.css', ['version' => false]);
echo $asset->url;  // '/assets/style.css' (no ?v=... parameter)

// In PHP
$asset = $assets->getAsset('style.css', ['version' => false]);

// In Latte
{asset 'style.css', version: false}

interface Mapper
{
	/**
	 * @throws Nette\Assets\AssetNotFoundException
	 */
	public function getAsset(string $reference, array $options = []): Nette\Assets\Asset;
}

public static function createAssetFromUrl(
	string $url,           // The public URL of the asset
	?string $path = null,  // Optional local file path (for reading properties)
	array $args = []       // Additional constructor arguments
): Asset

class DatabaseMapper implements Mapper
{
	public function __construct(
		private Connection $db,
		private string $baseUrl,
		private Storage $storage,
	) {}

	public function getAsset(string $reference, array $options = []): Asset
	{
		// Find asset in database
		$row = $this->db->fetchRow('SELECT * FROM assets WHERE id = ?', $reference);
		if (!$row) {
			throw new AssetNotFoundException("Asset '$reference' not found in database");
		}

		$url = $this->baseUrl . '/file/' . $row->storage_path;
		$localPath = $this->storage->getLocalPath($row->storage_path);

		return Helpers::createAssetFromUrl(
			url: $url,
			path: $localPath,
			args: [
				'mimeType' => $row->mime_type,
				'width' => $row->width,
				'height' => $row->height,
			]
		);
	}
}

class S3Mapper implements Mapper
{
	public function __construct(
		private S3Client $s3,
		private string $bucket,
		private string $region,
		private bool $private = false
	) {}

	public function getAsset(string $reference, array $options = []): Asset
	{
		try {
			// Check if object exists
			$this->s3->headObject([
				'Bucket' => $this->bucket,
				'Key' => $reference,
			]);

			if ($this->private) {
				// Generate presigned URL for private files
				$url = $this->s3->createPresignedRequest(
					$this->s3->getCommand('GetObject', [
						'Bucket' => $this->bucket,
						'Key' => $reference,
					]),
					'+10 minutes'
				)->getUri();
			} else {
				// Public URL
				$url = "https://s3.{$this->region}.amazonaws.com/{$this->bucket}/{$reference}";
			}

			return Helpers::createAssetFromUrl($url);

		} catch (S3Exception $e) {
			throw new AssetNotFoundException("Asset '$reference' not found in S3");
		}
	}
}

public function getAsset(string $reference, array $options = []): Asset
{
	$thumbnail = $options['thumbnail'] ?? null;

	$url = $thumbnail
		? $this->cdnUrl . '/thumb/' . $reference
		: $this->cdnUrl . '/' . $reference;

	return Helpers::createAssetFromUrl($url);
}

// Get normal image
$photo = $assets->getAsset('cdn:photo.jpg');

// Get thumbnail version
$thumbnail = $assets->getAsset('cdn:photo.jpg', ['thumbnail' => true]);

// In Latte: {asset 'cdn:photo.jpg', thumbnail: true}

class FallbackMapper implements Mapper
{
	public function __construct(
		private array $mappers
	) {}

	public function getAsset(string $reference, array $options = []): Asset
	{
		foreach ($this->mappers as $mapper) {
			try {
				return $mapper->getAsset($reference, $options);
			} catch (AssetNotFoundException) {
				// continue
			}
		}

		throw new AssetNotFoundException("Asset '$reference' not found in any source");
	}
}

www/
├── assets/
│   └── logo.png
└── index.php
latte
<div style="background-image: url({asset 'images/bg.jpg'})">
	Content
</div>

<img srcset="{asset 'images/[email protected]'} 2x">
latte
{* Uses the 'images' mapper (via prefix) *}
{asset 'images:product-photo.jpg'}

{* Uses the 'images' mapper (via array syntax) *}
{asset ['images', 'product-photo.jpg']}
latte
{var $banner = tryAsset('images/summer-sale.jpg')}
{if $banner}
	<div class="banner">
		<img src={$banner} alt="Summer Sale">
	</div>
{/if}

{* Or with a fallback *}
<img n:asset="tryAsset('user-avatar.jpg') ?? asset('default-avatar.jpg')" alt="Avatar">