fate/Silex-Extensions — Issue #9: AsseticExtension : "path_to_assets" + factory "AutoRegistration"
Author: gcrico
Created: 2011-11-22 15:12:23+00:00
State: open

Hi,

The AssetFactory's constructor first argument is a path to the "root" dir of the assets.
So we sould not use "path_to_web" as the first argument, but an other config option ("assetic.path_to_assets"?).

```php
// SilexExtension/AsseticExtension.php

--- $factory = new AssetFactory($app['assetic.path_to_web'], $options['debug']);
+++ $factory = new AssetFactory($app['assetic.path_to_assets'], $options['debug']);
```

```php
// Root directory for loading assets (when relative path are provided)
$app['assetic.path_to_assets'] = __DIR__ . '/assets';
// Location where to dump all generated files
$app['assetic.path_to_web'] = $app['web_dir'];
```

I wrote a special "Assetic Factory Worker" (see code below) that **adds the asset created with the AssetFactory to the provided AssetManager**.
So we can do :

```php
$app['assetic']->addWorker(
new \SilexExtension\AsseticAutoRegisterWorker($app['assetic.path_to_web'], $app['assetic.asset_manager'])
);
```

With this system, we can use the assetic twig extension functions quite easily, without declaring assets in the app, nor using any "FormulaLoader" on the templates.

Example :

```html

{% stylesheets 'Twitter-bootstrap/lib/bootstrap.less' filter='less,?yui_css' output='/css/*.css' %}

{% endstylesheets %}

```

When the twig template is parsed, the AssetFactory#createAsset() is invoked, which calls the Worker.

Note that the asset is added to the asset manager (and will be generated) only at **template compile time**!

So it's quite fast, but one may need to disable twig cache during developpment (to be usable).

```php
$app['twig.options'] = array(
'cache' => $app['debug'] ? null : $app['cache_dir'] . '/twig',
'debug' => $app['debug'],
);
```

Here is the AsseticAutoRegisterWorker class :

(The "path_to_web" and the "only if modified" stuff could be removed, to keep it simple.)

```php
path_to_web = $path_to_web;
$this->am = $am;
}

/**
* Processes an Asset Collection.
* @param AssetInterface $asset
* @return null
*/
public function process(AssetInterface $asset) {
if (! $asset instanceof AssetCollectionInterface) {
// Applied only on Asset Collections! We do not want to write "leafs"...
return;
}

// get the real targetPath
$targetPath = $this->path_to_web . '/' . $asset->getTargetPath();

// add to AssetManager only if modified, comparing "LastModified".
if (! file_exists($targetPath) || filemtime($targetPath) < $asset->getLastModified()) {
//echo '

UPDATING: '.htmlspecialchars(print_r($asset->getTargetPath(), true)).'

';
$name = 'AutoRegistered' . (++self::$nameSequencer);
$this->am->set($name, $asset);
}
}
}
```

*Sorry not being able to provide a "pull request". Git newbie. And I extracted the code above from a deep "fork in the hurry"...*