How to reuse code across multiple domains?

好久不见. 提交于 2019-12-05 21:01:56

Yes, Yii supports this. In fact, this is how I have some websites configured.

(Of course, this is predicated on having all your sites on the same server. But I see that Evan has this. This would not work accross servers.)

Firstly, it would require that you move your code out of the web-root and into the document root. See here.

Secondly, it requires that you use Yii AssetsBase. See here and there. I found the asset management a bear to configure (but a breeze to work with). This is what I ended up with:

In components/Controller.php include the following:

    /**
     * @var registers which js, css, images have been published
     * See: http://www.yiiframework.com/wiki/311/assetmanager-clearing-browser-s-cache-on-site-          update/
 */

    private $_assetsBase;

    public function getAssetsBase()
    {
            if ($this->_assetsBase === null) {
                Yii::app()->assetManager->newDirMode = 0755;        
                Yii::app()->assetManager->newFileMode = 0644;        

                    $this->_assetsBase = Yii::app()->assetManager->publish(
                            Yii::getPathOfAlias('application.assets'),
                            false,
                            -1,
                            defined('YII_DEBUG') && YII_DEBUG
                    );
            }
            return $this->_assetsBase;
    }

The above presupposes that your JS, CSS and images are located as follows:

protected/assets/js/mobiscroll-2.3.custom.min.js
protected/assets/css/mobiscroll-2.3.custom.min.css
protected/assets/img/einstein.png

Then in your views, call your assets as follows:

<?php
$cs->registerScriptFile($this->assetsBase.'/js/mobiscroll-2.3.1/js/mobiscroll-2.3.custom.min.js');
$cs->registerCssFile($this->assetsBase.'/js/mobiscroll-2.3.1/css/mobiscroll-2.3.custom.min.css');
?>

<img src="<?php echo $this->assetsBase ?>/img/einstein.png">

Finally, after you have made changes to your JS or CSS, you will want to force a cache refresh in all users' browsers. You do this by touching the (original) assets directory. This will force Yii to rehash the (published) assets directory. Subsequently, your JS & CSS will be refreshed in all users' browsers. Do something like this:

$command = 'touch /path/to/your/website/protected/assets';
exec ( $command.' 2>&1',  $output , $result  );
if ($result === 0) {
    $message = 'Assets have been pointed; a new directory should now be hashed';
} else {
    $message = 'Looks like something went wrong. Assets not pointed?';
} // END if
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!