我有这个我正在研究的课程,它允许你创建一个像这样的资产数组:
array(
'css' => array(
array('name' => 'bla'),
array('name' => 'bla2')
),
'js' => array(
array('name' => 'bla.js'),
array('name' => 'bla2.js')
)
);
然后该类解析这些并呈现出来,您将执行以下操作:
$assets = new AssetLoader(array(
'css' => array(
array('name' => 'bla'),
array('name' => 'bla2')
),
'js' => array(
array('name' => 'bla.js'),
array('name' => 'bla2.js')
)
));
$assets->renderAssets();
因此,假设您在应用程序的header.php中执行此操作,现在您有两个css文件和两个js文件。
如果您想创建新资产,请执行以下操作:
$assets->createAssets('css', array('name' => 'bla3'));
createAssets的问题是:
bla3
,作为js和css资产,实际上你告诉它创建一个新的css资产。renderAssets();
这是一个问题,您应该可以在应用程序的任何位置执行此操作,因此名称为:createAssets()
这是我的班级:
<?php
class AssetLoader {
private $assets;
private $cssAssets;
private $jsAssets;
public function __construct(array $assets){
$this->assets = $assets;
$this->seperateAssets($this->assets);
}
public function renderAssets(){
$this->renderCss();
$this->renderJs();
}
public function createAssets($type, array $assets){
if(isset($this->assets[$type])){
array_push($this->assets[$type], $assets);
$this->seperateAssets($this->assets);
}
}
protected function renderCss(){
foreach($this->processCss() as $css){
echo $css;
}
}
protected function renderJs(){
foreach($this->processJs() as $js){
echo $js;
}
}
protected function processCss(){
$html = array();
foreach($this->cssAssets as $assetName){
foreach($assetName as $name=>$location){
$html[] = '<link rel="stylesheet" type="text/css" name="'.$name.'" href="'.$location.'" />';
}
}
return $html;
}
protected function processJs(){
$html = array();
foreach($this->cssAssets as $assetName){
foreach($assetName as $name=>$location){
$html[] = '<script type="text/javascript" name="'.$name.'" src="'.$location.'"></script>';
}
}
return $html;
}
private function seperateAssets(array $assets){
$this->seperateCss($assets);
$this->seperateJs($assets);
}
private function seperateCss($assets){
foreach($assets as $key=>$value){
if($key == 'css'){
$this->cssAssets = $value;
}
}
}
private function seperateJs($assets){
foreach($assets as $key=>$value){
if($key == 'js'){
$this->jsAssets = $value;
}
}
}
}
我必须做出哪些更改才能使 A) createAsset()
在应用程序中的任何位置创建资产,而不是在调用renderAssets()
之前创建资产在标题中调用。和B)为你创建的资产添加到你定义的类型,在上面的例子中你看到我正在为css创建一个新的资产,这个资产如何被添加到css和js。
答案 0 :(得分:2)
在processJs()
方法中,更改此内容:
foreach($this->cssAssets as $assetName){
对此:
foreach($this->jsAssets as $assetName){