<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JSToolbox - все о JavaScript &#187; Phing</title>
	<atom:link href="http://www.jstoolbox.com/category/phing/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jstoolbox.com</link>
	<description>Блог о программировании вообще и о JavaScript в частности, уроки, статьи, заметки, база знаний.</description>
	<lastBuildDate>Wed, 28 Jul 2010 22:33:40 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Сжатие JavaScript/CSS файлов при помощи Phing</title>
		<link>http://www.jstoolbox.com/2009/10/18/szhatie-js-css-fajlo-pri-pomoshhi-phing/</link>
		<comments>http://www.jstoolbox.com/2009/10/18/szhatie-js-css-fajlo-pri-pomoshhi-phing/#comments</comments>
		<pubDate>Sun, 18 Oct 2009 15:38:42 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Phing]]></category>
		<category><![CDATA[Оптимизация]]></category>

		<guid isPermaLink="false">http://www.jstoolbox.com/?p=508</guid>
		<description><![CDATA[<p>В последнее время я имел возможность поработать с <a href="http://phing.info" title="Phing">Phing</a> - программой для сборки приложений. С её помощью можно копировать файлы приложения, заменять в них текст (например параметры конфигурационных файлов), и многое другое. Помимо прочего, можно самому создать подключаемые плагины, которые будут выполнять нужные нам задания. Мне нужно было при копировании таблиц стилей и скриптов выполнять их сжатие при помощи <a href="developer.yahoo.com/yui/compressor/" title="YUI compressor">YUI компрессора</a>, и я нашел отличное <a href="http://www.thepopeisdead.com/main/comments/easy_javascript_css_compression_with_phing/">решение</a> для этого.</p>]]></description>
			<content:encoded><![CDATA[<p>В последнее время я имел возможность поработать с <a href="http://phing.info" title="Phing">Phing</a> &#8211; программой для сборки приложений. С её помощью можно копировать файлы приложения, заменять в них текст (например параметры конфигурационных файлов), и многое другое. Помимо прочего, можно самому создать подключаемые плагины, которые будут выполнять нужные нам задания. Мне нужно было при копировании таблиц стилей и скриптов выполнять их сжатие при помощи <a href="http://developer.yahoo.com/yui/compressor/" title="YUI compressor">YUI компрессора</a>, и я нашел отличное <a href="http://www.thepopeisdead.com/main/comments/easy_javascript_css_compression_with_phing/">решение</a> для этого.</p>
<p><span id="more-508"></span></p>
<p>Представленный ниже плагин перед копированием сжимает скрипты и стили. Но учтите, что YUI-Compressor требует, чтобы была установлена Java:</p>
<pre class="prettyprint">
&lt;?php
/**
 * Uses the Phing Task
 */
require_once 'phing/Task.php';

/**
 * Task to compress files using YUI Compressor.
 *
 * @author      Keith Pope
 */
class kpMinTask extends Task
{
    /**
     * path to YuiCompressor
     *
     * @var  string
     */
    protected $yuiPath;

    /**
     * the source files
     *
     * @var  FileSet
     */
    protected $filesets    = array();

    /**
     * Whether the build should fail, if
     * errors occured
     *
     * @var boolean
     */
    protected $failonerror = false;

    /**
     * directory to put minified javascript files into
     *
     * @var  string
     */
    protected $targetDir;

    /**
     * sets the path where JSmin can be found
     *
     * @param  string  $yuiPath
     */
    public function setYuiPath( $yuiPath )
    {
        $this->yuiPath = $yuiPath;
    }

    /**
     *  Nested creator, adds a set of files (nested fileset attribute).
     */
    public function createFileSet()
    {
        $num = array_push( $this->filesets, new FileSet() );
        return $this->filesets[$num - 1];
    }

    /**
     * Whether the build should fail, if an error occured.
     *
     * @param boolean $value
     */
    public function setFailonerror( $value )
    {
        $this->failonerror = $value;
    }

    /**
     * sets the directory compressor traget dir
     *
     * @param  string  $targetDir
     */
    public function setTargetDir( $targetDir )
    {
        $this->targetDir = $targetDir;
    }

    /**
     * The init method: Do init steps.
     */
    public function init()
    {
        return true;
    }

    /**
     * The main entry point method.
     */
    public function main()
    {
        $command = 'java -jar {yuipath} {src} -o {target}';

        foreach( $this->filesets as $fs )
        {
            try
            {
                $files    = $fs->getDirectoryScanner( $this->project )->getIncludedFiles();
                $fullPath = realpath( $fs->getDir( $this->project ) );

                foreach( $files as $file )
                {
                    $this->log( 'Minifying file ' . $file );

                    $target = $this->targetDir . '/' . str_replace( $fullPath, '', $file );

                    if( file_exists( dirname( $target ) ) == false )
                    {
                        mkdir( dirname( $target ), 0700, true );
                    }

                    $cmd = str_replace( '{src}', $fullPath . DIRECTORY_SEPARATOR . $file, $command );
                    $cmd = str_replace( '{target}', realpath( $target ), $cmd );
                    $cmd = str_replace( '{yuipath}', realpath( $this->yuiPath ), $cmd );

                    $output = array();
                    $return = null;

                    exec( $cmd, $output, $return );

                    foreach( $output as $line )
                    {
                        $this->log( $line, Project::MSG_VERBOSE );
                    }

                    if( $return != 0 )
                    {
                      throw new BuildException( "Task exited with code $return" );
                    }

                }
            } 

            catch( BuildException $be )
            {
                // directory doesn't exist or is not readable
                if ($this->failonerror)
                {
                    throw $be;
                }
                else
                {
                    $this->log($be->getMessage(), $this->quiet ? Project::MSG_VERBOSE : Project::MSG_WARN);
                }
            }
        }
    }
}
</pre>
<p>Сохраните этот файл в папке <strong>build/extended/tasks/kpMinTask.php</strong>, а <em>yuicompressor</em> в <strong>build/tools/yuicompressor.jar</strong>. Здесь, <strong>build</strong> &#8211; это папка, в которой находится XML файл сборки.</p>
<p>Далее, в файле сборки <em>build.xml</em> добавляем задачи для сжатия:</p>
<pre class="prettyprint">
&lt;taskdef name="minify" classname="extended.tasks.kpMinTask" /&gt;

&lt;target name="minify-js"&gt;
    &lt;echo&gt;--------------------------------&lt;/echo&gt;
    &lt;echo&gt;| Minify javascript to release |&lt;/echo&gt;
    &lt;echo&gt;--------------------------------&lt;/echo&gt;
    &lt;minify targetDir="${DEPLOY_DIR}/public/js/"
              yuiPath="tools/yuicompressor.jar"&gt;
        &lt;fileset dir="${TRUNK_PATH}/public/"&gt;
                &lt;include name="js/*.js" /&gt;
                &lt;include name="js/**/*.js" /&gt;
        &lt;/fileset&gt;
    &lt;/minify&gt;
&lt;/target&gt;

&lt;target name="minify-css"&gt;
    &lt;echo&gt;--------------------------------&lt;/echo&gt;
    &lt;echo&gt;| Minify CSS to release |&lt;/echo&gt;
    &lt;echo&gt;--------------------------------&lt;/echo&gt;
    &lt;minify targetDir="${DEPLOY_DIR}/public/"
              yuiPath="tools/yuicompressor.jar"&gt;
        &lt;fileset dir="${TRUNK_PATH}/public/css/"&gt;
                &lt;include name="css/**/*.css" /&gt;
                &lt;include name="css/*.css" /&gt;
        &lt;/fileset&gt;
    &lt;/minify&gt;
&lt;/target&gt;
</pre>
<p>Теперь, для выполнения сжатия/копирования файлов нужно запустить задачу <em>minify-js</em> или <em>minify-css</em> или включить их в другую задачу.</p>
<p>Если у вас нет возможности использовать YUI-Compressor (например нет java на хостинге), то можете воспользоваться другими скриптами: <a href="http://code.google.com/p/jsmin-php/" title="JSMin">JSMin</a> и <a href="http://code.google.com/p/cssmin/">CSSMin</a>. Подробнее о том, как их использовать вместе с Phing читайте <a href="http://www.simplecoding.org/ispolzovanie-phing-dlya-sborki-web-prilozhenij.html" title="Использование Phing для сборки web приложений">здесь</a>.</p>
<div class="postLinks"><strong>При поддержке:</strong><br/><br />
stihi2.ru  &#8211; <a href=http://stihi2.ru/>стихи эпиграммы</a>,<br />
losty.ru  &#8211; <a href=http://losty.ru/razdel/novyigod.php>стихи про новый год</a>,<br />
full-house.ru  &#8211; <a href=http://full-house.ru/>стихи хокку</a></div>
]]></content:encoded>
			<wfw:commentRss>http://www.jstoolbox.com/2009/10/18/szhatie-js-css-fajlo-pri-pomoshhi-phing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
