fuelphp-casset
文件大小: unknow
源码售价: 5 个金币 积分规则     积分充值
资源说明:Better asset management library for fuelphp (with minification!)
Casset
======

Casset is an alternative to fuelphp's Asset class.  
Casset supports minifying and combining scripts, in order to reduce the number and size of http requests need to load a given page. Grouping syntax has been made cleaner, and the ability to render all groups, and enable/disable specific groups, added.  
There are are some other changes too, please read on!

Thanks to Stephen Clay (and Douglas Crockford) for writing the minification libraries, stolen from http://code.google.com/p/minify/.

If you have any comments/queries, either send me a message on github, post to the fuelphp [forum thread](http://fuelphp.com/forums/topics/view/2187), catch me on #fuelphp, or open an issue.

If you're just after a quick reference, or a reminder of the API, see the the file `quickref.md`.

Installation
------------

### Using oil
1. cd to your fuel project's root
2. Run `php oil package install casset`
3. Optionally edit fuel/packages/casset/config/casset.php (the defaults are sensible)
4. Create public/assets/cache
5. Add 'casset' to the 'always_load/packages' array in app/config/config.php (or call `Fuel::add_package('casset')` whenever you want to use it).
6. Enjoy :)

### Manual (may be more up-to-date)
1. Clone (`git clone git://github.com/canton7/fuelphp-casset`) / [download](https://github.com/canton7/fuelphp-casset/zipball/master)
2. Stick in fuel/packages/
3. Optionally edit fuel/packages/casset/config/casset.php (the defaults are sensible)
4. Create public/assets/cache
5. Add 'casset' to the 'always_load/packages' array in app/config/config.php (or call `Fuel::add_package('casset')` whenever you want to use it).
6. Enjoy :)

If you don't want to change the config file in `fuel/packages/casset/config/casset.php`, you can create your own config file in `fuel/app/config/casset.php`.
You can either copy the entirely of the original config file, or just override the keys as you like.
The magic of Fuel's `Config` class takes care of the rest.

Introduction
------------

Casset is an easy-to-use asset management library. It boasts the following features:

- Speficy which assets to use for a particular page in your view/controller, and print them in your template.
- Collect your assets into groups, either pre-defined or on-the-fly.
- Enable/disable specific groups from your view/controller.
- Minify your groups and combine into single files to reduce browser requests and loading times.
- Define JS/CSS in your view/controller to be included in your template.
- Namespace your assets.

Basic usage
-----------

JS and CSS files are handled the same way, so we'll just consider JS. Just substitude 'js' with 'css' for css-related functions.

Javascript files can be added using the following, where "myfile.js" and "myfile2.js" are the javascript files you want to include,
and are located at public/assets/js/myfile.js and public/assets/js/myfile2.js (configurable).

```php
Casset::js('myfile.js');
Casset::js('myfile2.js');
```

By default, Casset will minify both of these files and combine them into a single file (which is written to public/assets/cache/\.js).
To include this file in your page, use the following:

```php
echo Casset::render_js();
/*
Returns something like

*/
```

If you've got minification turned off (see the section at the bottom of this readme), you'll instead get:

```php


```

If you have a specific file ("myfile.min.js") which you want Casset to use, rather than generating its own minified version, you
can pass this as the second argument, eg:

```php
Casset::js('myfile.js', 'myfile.min.js');
```

Some folks like css and js tags to be together. `Casset::render()` is a shortcut which calls `Casset::render_css()` then `Casset::render_js()`.

Images
------

Although the original Asset library provided groups, etc, for dealing with images, I couldn't see the point.

Therefore image handling is somewhat simpler, and can be summed up by the following line, where the third argument is an optional array of attributes:

```php
echo Casset::img('test.jpg', 'alt text', array('width' => 200));
```

You can also pass an array of images (which will all have to same attributes applied to them), eg:

```php
echo Casset::img(array('test.jpg', 'test2.jpg'), 'Some thumbnails');
```

This function has more power when you consider namespacing, detailed later.

Groups
------

Groups are collections of js/css files.
A group can be defined in the config file, or on-the-fly. They can be enabled and disabled invidually, and rendered individually.

CSS and JS have their own group namespaces, so feel free to overlap.

To define a group in the config file, use the 'groups' key, eg:

```php
'groups' => array(
	'js' => array(
		'group_name' => array(
			'files' => array(
				array('file1.js', 'file1.min.js'),
				'file2.js'
			),
			'combine' => false,
			'min' => false,
			'inline' => true
		),
		'group_name_2' => array(.....),
	),
	'css' => array(
		'group_name' => array(
			'files' => array(
				array('file1.css', 'file1.min.css'),
				'file2.css',
			),
			'enabled' => false,
			'attr' => array('media' => 'print'),
			'deps' => array('some_group'),
		),
		'group_name_3' => array(.....),
	),
),
```

As you can see, the javascript and css groups are entirely separate.
Each group consists of the following parts:  
**files**: a list of files present in the group. Each file definition can either be a string or a 2-element array.
If you're using minification, but have a pre-minified copy of your file (jquery is an example), you can pass this as the second
array element.  
**enabled**: Optional, specifies whether a group is enabled. A group will only be rendered when it is enabled. Default true.  
**combine**: This optional key allows you to override the 'combine' config key on a per-group bases.  
**min**: This optional key allows you to override the 'min' config key on a per-group basis.  
**inline**: Optional, allows you to render the group 'inline' -- that is, show the CSS directly in the file, rather than including a separate .css file. See the section on inling below.  
**attr**: Optional, allows you to specify extra attributes to be added to the script/css/link tag generated. See the section on attributes below.  
**deps**: (Optional) Specifies other groups to be rendered whenever this group is rendered, see the section below.

Aside: You can specify any non-string value for the asset name, and it will be ignored.
This can be handy if you're doing something like `'files' => array(($var == $val) ? false : 'file.js')`.

Groups can be enabled using `Casset::enable_js('group_name')`, and disabled using `Casset::disable_js('group_name')`. CSS equivalents also exist.  
The shortcuts `Casset::enable('group_name')` and `Casset::disable('group_name')` also exist, which will enable/disable both the js and css groups of the given name, if they are defined.  
You can also pass an array of groups to enable/disable.

Specific groups can be rendered using eg `Casset::render_js('group_name')`. If no group name is passed, *all* groups will be rendered.  
Note that when a group is rendered, it is disabled. See the "Extra attributes" section for an application of this behaviour.

Files can be added to a group by passing the group name as the third argument to `Casset::js` / `Casset::css`, eg:

```php
Casset::js('myfile.js', 'myfile.min.js', 'group_name');
Casset::css('myfile.css', false, 'group_name');
```

(As an aside, you can pass any non-string value instead of 'false' in the second example, and Casset will behave the same: generate your minified file for you.)

If the group name doesn't exist, the group is created, and enabled.

You can also add groups on-the-fly using `Casset::add_group($group_type, $group_name, $files, $options)`, where `$options`is an array with *any* of the following keys:

```php
$options = array(
	'enabled' => true/false,
	'min' => true/false,
	'combine' => true/false,
	'inline' => true/false,
	'attr' => array(),
	'deps' => array(),
);
```

The arguments are the same as for the config key -- if `'enabled'`, `'combine'` or `'min'` are omitted, the value specified in the config file are used. Eg:

```php
Casset::add_group('test_group', array(
	array('file1.js', 'file1.min.js'),
	'file2.js',
));
```

This method is provided merely for convenience when adding lots of files to a group at once.
You don't have to create a group before adding files to it -- the group will be created it it doesn't exist.

You can change any of these options on-the-fly using `Casset::set_group_option($type, $group, $key, $value)`, or the CSS- and JS- specific versions, `Casset::set_js_option($group, $key, $value)` and `Casset::set_css_option($group, $key, $value)`.
`$group` has some special values: an empty string is a shortcut to the 'global' group (to which files are added if a group is not specified), and '*' is a shortcut to all groups.
Multiple group names can also be specified, using an array.

Examples:

```php
// Add a dep to the my_plugin group
Casset::set_js_option('my_plugin', 'deps', 'jquery');

// Make all files added to the current page using Casset::add_css() display inline:
Casset::set_css_option('', 'inline', true);

// Turn off minification for all groups, regardless of per-group settings, for the current page:
Casset::set_js_option('*', 'min', false);
```

When you call `Casset::render()` (or the js- and css-specific varients), the order that groups are rendered is determined by the order in which they were created, with groups present in the config file appearing first.
Similarly (for JS files only), the order in which files appear is determined by the order in which they were added.
This allows you a degree of control over what order your files are included in your page, which may be necessary when satisfying dependencies.
If this isn't working for you, or you want something a bit more explicit, try this: If file A depends on B, add B to its own group and explicitely render it first.

NOTE: Calling ``Casset::js('file.js')`` will add that file to the "global" group. Use / abuse as you need!

NOTE: The arguments for `Casset::add_group` used to be different. Backwards compatibilty is maintained (for now), but you are encouranged to more to the new syntax.

Paths and namespacing
---------------------

The Asset library searches through all of the items in the 'paths' config key until it finds the first matching file.
However, this approach was undesirable, as it means that if you had the directory structure below, and tried to include 'index.js', the file that was included would be determined by the order of the
entries in the paths array.

```
assets/
   css/
   js/
      index.js
   img/
   admin/
      css/
      js/
	     index.js
      img/
```

Casset brings decent namespacing to the rescue!
For the above example, you can specify the following in your config file:

```
'paths' => array(
	'core' => 'assets/',
	'admin' => 'assets/admin/',
),
```

You can also add paths on-the-fly using `Casset::add_path($key, $path)`, eg.

```php
Casset::add_path('admin', 'assets/admin/');
```

Which path to use is then decided by prefixing the asset filename with the key of the path to use. Note that if you omit the path key, the current default path key (initially 'core') is used.

```php
Casset::js('index.js');
// Or
Casset::js('core::index.js');
// Will add assets/js/index.js

Casset::js('admin::index.js');
// Will add assets/admin/js/index.js

echo Casset::img('test.png', 'An image');
// An image

echo Casset::img('admin::test.png', 'An image');
// An image
```

If you wish, you can change the current default path key using `Casset::set_path('path_key')`. This can be useful if you know that all of the assets in a given file will be from a given path. For example:

```php
Casset::set_path('admin);
Casset::js('index.js');
// Will add assets/admin/js/index.js
```

The "core" path can be restored by calling `Casset::set_path()` with no arguments (or calling `Casset::set_path('core')`).

You can also namespace the files listed in the config file's 'groups' section, in the same manner.
Note that these are loaded before the namespace is changed from 'core', so any files not in the core namespace will have to by explicitely prepended with the namespace name.

In addition, you can override the config options 'js_path', 'css_path' and 'img_path' on a per-path basis. In this case, the element of the 'paths' config array takes the following form,
where each of 'js_path', 'css_path' and 'img_path' are optional. If they are not specified, the defaults will be used.

```php
array (
	'some_key' => array(
		'path' => 'more_assets/',
		'js_dir' => 'javascript/',
		'css_dir' => 'styles/',
		'img_dir' => 'images/',
	),
),
```

This can be particularly useful when you're using some third-party code, and don't have control over where the assets are located.

Note also that you can add an asset which uses a path which isn't yet defined.
Casset only requires that the path is defined by the time the file is rendered.

If you add an asset whose path starts with a leading slash, the folder specified by 'js_dir', 'css_dir', etc (either in the config or in the namespace), is ignored.
This can be handy if you have a third-party module which, for example, puts css inside the js/ folder.
For example:

```php
Casset::js('some_key::file.js')
// Adds more_assets/javascript/file.js
Casset::js('some_key::/file.js')
// Adds more_assets/file.js
```

Globbing
--------

As well as filenames, you can specify [glob patterns](http://php.net/glob). This will act exactly the same as if each file which the glob matches had been added individually.  
For example:

```php
Casset::css('*.css');
// Runs glob('assets/css/*.css') and adds all matches.

Casset::css('admin::admin_*.css');
// (Assuming the paths configuration in the "Paths and namespacing" section)
// Executes glob('adders/admin/css/admin_*.css') and adds all matches

Casset::js('*.js', '*.js');
// Adds all js files in assets/js, ensuring that none of them are pre-minified.
```

An exception is thrown when no files can be matched.

Dependencies
------------

Casset allows you to specify dependancies between groups, which are automatically resolved.
This means that you can, say, define a group for your jQuery plugin, and have jQuery automatically included every time that plugin is included.

Note that dependancies can only be entire groups -- groups can not depend on individual files.
This has to do with how files are put into cache files, email me if you're interested.

A JS group can only depend on other JS groups, while a CSS group can only depend on other CSS groups.

Casset is pretty intelligent, and will only include a file once, before the file that requires it.
After a file has been required as a dependency, it will be disabled.
Casset will also bail after following the dependency chain through a certain number of steps, to avoid cycling dependancies.
This value is given by the config key 'deps_max_depth'.

The easiest way of specifying dependancies is through the config file:

```php
'groups' => array(
	'js' => array(
		'jquery' => array(
			'files' => array(
				array('jquery.js', 'jquery.min.js'),
			),
		),
		
		'my_plugin' => array(
			'files' => array(
				'jquery.my_plugin.js',
			),
			'deps' => array(
				'jquery',
			),
		),
	),
),
```

Dependencies can be either a string (for a single dependency), or an array (for multiple ones).

You can also define dependencies when you call `Casset::add_group()`, by using the `'deps'` key in `$options`.

 Eg:
 
 ```php
Casset::add_group('js', 'my_plugin', array('jquery.my_plugin.js'), array(
	'deps' => 'jquery',
));
 ```

In addition, the functions `Casset::add_js_deps()` and `Casset::add_css_deps()` exist, which can be used like:

```php
Casset::add_js_deps('group_name', array('this', 'groups', 'deps'));
```

As usual, there's another base function, `Casset::add_deps()`, which takes 'js' or 'css' as its first argument, but is otherwise identical.

If you have a JS group A, which depends on both the JS group B and CSS group B, a useful trick is to create a CSS group A with no files, that depends on the CSS group B.
Therefore whenever group A is rendered, both the JS group B and CSS group B will be rendered.

Inlining
--------

If you want Casset to display a group inline, instead of linking to a cache file, you can mark the group as 'inline' when you create it.

```php
// In your config (see add_group also)
'groups' => array(
	'js' => array(
		'my_inline_group' => array(
			'files' => array('file.css'),
			'inline' => true,
		),
	),
),
```

NOTE: You could previously pass an argument to `Casset::render()` to tell it to render the group inline.
This behaviour has been deprecated, although it still works.
You are encouraged to move away from this technique if you are using it.

Occasionally it can be useful to declare a bit of javascript in your view, but have it included in your template. Casset allows for this, although it doesn't support groups and minification
(as I don't see a need for those features in this context -- give me a shout if you find an application for them, and I'll enhance).

In your view:

```php
$bar = 'baz';
$js = <<
	var foo = "baz";

*/
```

Similarly, `Casset::css_inline()` and `Casset::render_css_inline()` exist.

Extra attributes
----------------

If you want to apply extra attributes to the script/link tag, you can add them to the group config, using the key 'attr'.
For example:

```php
// In your config
'groups' => array(
	'css' => array(
		'my_print' => array(
			'files' => array('file.css'),
			'attr' => array('media' => 'print'),
		),
	),
),

// Render the 'my_print' group, along with the others
echo Casset::render_css();
// 
```

You can also pass them in the `$options` argument to `Casset::add_group()`, for example:

```php
Casset::add_group('js', 'my_deferred_js', array(
	'file.js',
	), array(
	'attr' => array(
		'defer' => 'defer',
	),
);

echo Casset::render_js();
// 
```

NOTE: You used to be able to pass an `$attr` argument to `Casset::render()`.
This behaviour has been deprecated, although it still works.
Please move to the new system.

Minification and combining
--------------------------

Minification uses libraries from Stephen Clay's [Minify library](http://code.google.com/p/minify/).

The 'min' and 'combine' config file keys work together to control exactly how Casset operates:

**Combine and minify:**
When an enabled group is rendered, the files in that group are minified (or the minified version used, if given, see the second parameter of eg `Casset::js()`),
and combined into a single cache file in public/assets/cache (configurable).

**Combine and not minify:**
When an enabled group is rendered, the files in that group are combined into a a single cache file in public/assets/cache (configurable). The files are not minified.

**Not combine and minify:**
When an enabled group is rendered, a separate `
// 

// If minification is enabled:
// 
// 
```

Getting asset paths / urls
--------------------------

Thanks to [Peter](http://fuelphp.com/forums/posts/view_reply/3097) for this one. You can ask Casset for the path / url to a specific file.
Files are specified in exactly the same way as with eg `Casset::js()`, with the same rules to do with namespacing, `Casset::set_path()`, etc.

The functions in question are `Casset::get_filepath_js()`, `Casset::get_filepath_css()`, and `Casset::get_filepath_img()`.

They're all used in the same way:

```php
echo Casset::get_filepath_js('file.js');
// assets/js/file.js
```

Note that fuel executes in the `/public` directory, so the paths returned are relative to the current working dir.
If you'd prefer urls to be returned, pass `true` as the second parameter.
Note that a url will not be added if you're referencing a remote file.

```php
echo Casset::get_filepath_js('file.js', true);
// eg http://localhost/site/public/assets/js/file.js
```

Complexities start arising when you specify globs.
By default, an array will be returned if more than one file is found, otherwise a string is returned.
To override this behaviour, and return an array even if only one file is found, pass `true` as the third parameter.

```php
print_r(Casset::get_filepath_js('file.js', false, true));
// Array( [0] => 'assets/js/file.js' )

print_r(Casset::get_filepath_js('file*.js'));
// Array( [0] => 'assets/js/file1.js', [1] => 'assets/js/file2.js' )
```

There also exists `Casset::get_filepath()`, which takes the form

```php
Casset::get_filepath($name, $type, $add_url = false, $force_array = false);
```

`$name`, `$add_url` and `$force_array` are the same as for `Casset::get_filepath_js()`, while the `$type` argument is one of 'js', 'css', or 'img'.
In the future there are plans to let you specify your own types, hence why this is exposed :)

Controlling whether tags are generated
--------------------------------------

Thanks to antitoxic for motivating this feature.

The `get_filepath_*` functions are useful if you want to link directly to an asset.
However, this doesn't cover the case where you want to, for whatever reason, generate your own `
Casset::render_js(false, array('gen_tags' => false));
// Returns Array (
//   [0] => "http://....test_file.js"
// )

Casset::set_group_option('js', 'global', 'inline', true);
Casset::render_js(false);
// Returns 
Casset::render_js(false, array('gen_tags' => false));
// Returns Array (
//   [0] => "Some javascript file content"
// )
```

If more than one `



				
			
		
本源码包内暂不包含可直接显示的源代码文件,请下载源码包。