PHP Class Header Files Handle

01jun08

Escrevi uma classe para manusear a inclusão dos arquivos CSS e Javascript no cabeçalho das páginas. Ele funciona da seguinte maneira:

Imagina que você tenha 10 arquivos CSS, e queira substituir estas 10 inclusões (http_requests) por apenas 2 inclusões. Ou seja, 2 arquivos CSS onde cada um deles tenha embutido, o conteúdo de 5 dos arquivos anteriores. Bom, legal, se fosse só pra isso, bastaria você utilizar uma classe de PHP Minify por exemplo a do VulgarisOverIp.

Mas a grande jogada aqui está no agrupamento dos arquivos, ou seja, você conseguir definir quaise arquivos estarão juntos em cada Package (para fazer o balanceamento de requests x peso por arquivo). E flexibilizar o REBUILD de cada package específico, caso 1 dos arquivos do pacote seja atualizado no futuro (não sendo necessário assim, re-criar todos os pacotes).

O resultado final desta classe PHP é:

<!– EMBEDED SCRIPTS CSS *************************************************** –>
<link rel=”stylesheet” type=”text/css” href=”http://www.exemplo.com/css/style.pk0.min_v.1.0.css&#8221; media=”screen”/>
<link rel=”stylesheet” type=”text/css” href=”http://www.exemplo.com/css/style.pk1.min_v.1.0.css&#8221; media=”screen”/>

<!– EMBEDED SCRIPTS JAVASCRIPT ******************************************** –>
<script type=”text/javascript” src=”http://www.exemplo.com/js/javascript.pk0.min_v.1.0.js”></script&gt;
<script type=”text/javascript” src=”http://www.exemplo.com/js/javascript.pk1.min_v.1.0.js”></script&gt;
<script type=”text/javascript” src=”http://www.exemplo.com/js/javascript.pk2.min_v.1.0.js”></script&gt;

Olhando um pouco mais de perto, a estrutura funciona assim:

//Include the header files handle class file
include(PATH_CLASSES .’/class.headerfiles.php’);
$hFiles = new HeaderFiles;
$hFiles->path_root_CSS = ‘root/www/site/css’;
$hFiles->path_root_JS = ‘root/www/site/js’;
$hFiles->path_public_CSS = ‘http://www.example.com/css&#8217;;
$hFiles->path_public_JS = ‘http://www.example.com/js&#8217;;

// Setting the 2 packages of CSS files – do not use the enxtension file: .css (if the name is: style.css, just use style)
define(‘VERSION_CSS’, ‘1.0’);
define(‘SCRIPTS_CSS’, serialize(array(
‘0’=>array(‘file1’,
‘file2’,
‘1’=>array(‘file3’,
‘file4’,
‘file5’)
)));
define(‘REBUILD_CSS’, serialize(array(‘*’)));

// Generating Embeded CSS
$EMBEDED_SCRIPT_CSS = $hFiles->SetIncludeFiles(unserialize(SCRIPTS_CSS),’css’,VERSION_CSS,’site’,unserialize(REBUILD_CSS));

// Generating Embeded Javascript
// $EMBEDED_SCRIPT_JS = $hFiles->SetIncludeFiles(unserialize(SCRIPTS_JS),’js’,VERSION_JS,’site’,unserialize(REBUILD_JS));

echo $EMBEDED_SCRIPT_CSS;
// result: <link rel=”stylesheet” type=”text/css” href=”……

Para o caso do CSS, esta classe faz a função de MINIFY, retirando comentários e espaços em branco desnecessários dos arquivos CSS de origem. Porém, para os arquivos Javascript, ela apenas agrupa os arquivos dentro dos pacotes, sem fazer nenhuma alteração neles (reduzindo apenas o número de requisições HTTP).

O quê pode melhorar?

  • Incluir a chamada de alguma classe de MINIFY de Javascript, a fim de reduzir o tamanho (Kb) dos pacotes gerados.

Abaixo está o código completo da classe:

<?php

/**
* Project: headerFiles
* File: class.headerfiles.php
*
* Description:
*
* This class is used to manage CSS and JAVASCRIPT files in the header of the page.
* The main feature is not to compress or minify CSS and JS (but this class also do it).
*
* I was focused on really manage this files, what I mean is: Imagine that you
* have a set of 10 CSS files and 10 JS files, and you want to JOIN them into
* 2 packages of 5 files each. (CSS: pk0 , pk1 – JS: pk0, pk1)
*
* When you should to update one of these 5 files (of each pack), you can just
* rebuild the package number what it is inside (not the both package).
*
* With this class you can MINIFY some CSS files and JOIN JS files into some packages containing
* a certain number of files inside it.
*
* More practical:
define(‘VERSION_CSS’, ‘1.0’);
define(‘SCRIPTS_CSS’, serialize(array(
‘0’=>array(‘file1’,
‘file2’,
‘1’=>array(‘file3’,
‘file4’,
‘file5’)
)));
define(‘REBUILD_CSS’, serialize(array(‘*’)));
*
* This will generate 2 Packages (pk0 and pk1), with these CSS files inside it, without comments – minify version)
* The parameter ‘*’ is used to rebuild ALL Packages or generate it at the first time.
*
* If someday you update your ‘file2.css’, just rebuild the package 2 [ serialize(array(‘2’)) ]
* or if you need to Rebuild more than one package, use: [ serialize(array(‘2′,’3′,’4′)) ]
*
* @link https://hlibco.wordpress.com/
* @author Felipe Hlibco <hlibco at gmail dot com>
* @package Header
* @version 1.0.0
*/

/**
* USAGE EXAMPLE
* ————-

//Include the header files handle class file
include(PATH_CLASSES .’/class.headerfiles.php’);
$hFiles = new HeaderFiles;
$hFiles->path_root_CSS = ‘root/www/site/css’;
$hFiles->path_root_JS = ‘root/www/site/js’;
$hFiles->path_public_CSS = ‘http://www.example.com/css&#8217;;
$hFiles->path_public_JS = ‘http://www.example.com/js&#8217;;

// Setting the 2 packages of CSS files – do not use the enxtension file: .css (if the name is: style.css, just use style)
define(‘VERSION_CSS’, ‘1.0’);
define(‘SCRIPTS_CSS’, serialize(array(
‘0’=>array(‘file1’,
‘file2’,
‘1’=>array(‘file3’,
‘file4’,
‘file5’)
)));
define(‘REBUILD_CSS’, serialize(array(‘*’)));

// Generating Embeded CSS
$EMBEDED_SCRIPT_CSS = $hFiles->SetIncludeFiles(unserialize(SCRIPTS_CSS),’css’,VERSION_CSS,’site’,unserialize(REBUILD_CSS));

// Generating Embeded Javascript
// $EMBEDED_SCRIPT_JS = $hFiles->SetIncludeFiles(unserialize(SCRIPTS_JS),’js’,VERSION_JS,’site’,unserialize(REBUILD_JS));

echo $EMBEDED_SCRIPT_CSS;
*
*
*
*/

class HeaderFiles {

var $path_root_CSS;
var $path_root_JS;
var $path_public_CSS;
var $path_public_JS;

/* Public: Include CSS and Javascript files in the header */
/*
PARAMETERS:
$filenamePool: (string | array)
$fileType: (string) ‘css’ | ‘js’
$version: (string)
$pack : (integer) [0] Does not exists a default package [1] Exists a default package
$rebuild: (integer) [0] Do not rebuild ths script [1] Rebuild the script
*/
function SetIncludeFiles($packageFiles, $fileType, $version = ‘1.0’, $object = ‘site’, $rebuild = 0)
{
/* Validate Version */
if (empty($version)) { $version = ‘1.0’; }

/* Add file type default settings */
if ($fileType == ‘css’)
{
$preName = ‘style’;
$pathPublic = $this->path_public_CSS;
$pathRoot = $this->path_root_CSS;
}
elseif ($fileType == ‘js’)
{
$preName = ‘javascript’;
$pathPublic = $this->path_public_JS;
$pathRoot = $this->path_root_JS;
}

/* Identifying Object */
if ($object != ‘site’)
{
$pathPublic .= ‘/’ . $object;
$pathRoot .= ‘/’ . $object;
}

/* Get the files parsed */
if (!is_array($filenamePool) && !empty($filenamePool))
{
$filenamePool = array($filenamePool);
}

/* For each file parsed into package, loop */
foreach($packageFiles as $package=>$files)
{
/* Generate the filename for each object type */
if ($object == ‘site’)
{
$filename = $preName . ‘.pk’ . $package . ‘.min_v.’ . $version . ‘.’ . $fileType;
}
else
{
/* Just allow 1 script file per object (film / filmclub / theater) */
$filename = $packageFiles[0] . ‘.’ . $fileType;
}

/* Validate rebuild activation */
if (!is_array($rebuild)) { $rebuild = array(); }

/* Rebuild some specified package or Re-generate all packages ‘*’ */
if (in_array($package,$rebuild) || in_array(‘*’,$rebuild))
{
/* Handle Files from diferent way */
if ($fileType == ‘css’)
{
foreach($files as $file)
{
$content = file_get_contents($pathRoot . ‘/’ . $file . ‘.’ . $fileType);
$packageContent .= str_replace(‘; ‘,’;’,str_replace(‘ }’,’}’,str_replace(‘{ ‘,'{‘,str_replace(array(“\r\n”,”\r”,”\n”,”\t”,’ ‘,’ ‘,’ ‘),””,preg_replace(‘!/\*[^*]*\*+([^/][^*]*\*+)*/!’,”,$content)))));
}
}
elseif ($fileType == ‘js’)
{
foreach($files as $file)
{
$packageContent .= file_get_contents($pathRoot . ‘/’ . $file . ‘.’ . $fileType);
}
}

$fp = fopen($pathRoot . ‘/’.$filename, ‘w+’);
fwrite($fp, $packageContent);
fclose($fp);
unset($packageContent);
}

/* Generating Tag */
if ($fileType == ‘css’)
{
$outputTag .= ‘<link rel=”stylesheet” type=”text/css” href=”‘ . $pathPublic . ‘/’ . $filename . ‘” media=”screen”/>’ . “\r\n”;
}
elseif ($fileType == ‘js’)
{
$outputTag .= ‘<script type=”text/javascript” src=”‘ . $pathPublic . ‘/’ . $filename . ‘”></script>’ . “\r\n”;
}
}

/* Return the content */
return $outputTag;
}

}
?>



No Responses Yet to “PHP Class Header Files Handle”

  1. Deixe um comentário

Deixe uma resposta

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s


%d blogueiros gostam disto: