[英]What would be a good strategy for a variable for prefixing a static resource?
We are scaling a website and we would like to plan for the future where we may want to host our images in a sub-domain (or perhaps even a separate domain altogether, eg a CDN ). 我们正在扩展一个网站,我们希望计划未来我们可能希望在子域(或者甚至可能是一个单独的域,例如CDN )中托管我们的图像。 We currently reference images in our HTML/PHP code using the following HTML: 我们目前使用以下HTML在HTML / PHP代码中引用图像:
<img src="/images/ourlogo.jpg" alt="Our Logo" />
I was thinking of starting a company convention to move to: 我正在考虑启动公司大会,以便:
<img src="<?php echo STAT_IMG;?>ourlogo.jpg" alt="Our Logo" />
where STAT_IMG is a global PHP constant, which would be initially defined to be identical to the current situation, ie 其中STAT_IMG是一个全局PHP常量,最初定义为与当前情况相同,即
define('STAT_IMG', '/images/');
but could later be changed to something such as: 但后来可以改为:
define('STAT_IMG', 'http://www.superfastcdn.com/');
Will I run into any issues doing this? 我会遇到任何问题吗?
Things I have already thought about: 我已经考虑过的事情:
STAT_IMG
as "protocol-less", eg define('STAT_IMG', '//www.superfastcdn.com/');
来自encosia的这篇文章通过将STAT_IMG
定义为“无协议”来解决这个问题,例如define('STAT_IMG', '//www.superfastcdn.com/');
. 。 I hope their idea works. 我希望他们的想法有效。
define('STAT_IMGS', 'https://www.example.com/images/');
我们可能需要一些其他常量来明确定义协议,例如define('STAT_IMGS', 'https://www.example.com/images/');
and define('STAT_IMGNS', 'http://www.example.com/images/');
并define('STAT_IMGNS', 'http://www.example.com/images/');
in addition to the previous non-absolute version ( define('STAT_IMG', '/images/');
). 除了以前的非绝对版本( define('STAT_IMG', '/images/');
)。 It sounds like what you need is a function -- that's how this tends to be handled in frameworks like Rails, Symfony, and Django. 听起来你需要的是一个函数 - 这就是在Rails,Symfony和Django等框架中处理它的方式。 In general, encapsulating logic is a good idea, so you don't find yourself having to update more than place for a given design change. 一般来说,封装逻辑是一个好主意,因此您不必为给定的设计更改而更新自己。
For starters, you could put this in a location common across all templates: 对于初学者,您可以将其放在所有模板中通用的位置:
<?
$my_domain = "something.com";
function static_url($relative_path, $SSL=false) {
$prefix = $SSL ? 'https' : 'http';
return "{$prefix}://{$my_domain}{$relative_path}";
}
Then, you could put this a your template: 然后,你可以把它作为你的模板:
<img src="<?=static_url('images/ourlogo.jpg'); ?>" />
Or, if you need https: 或者,如果您需要https:
<img src="<?=static_url('images/ourlogo.jpg', true); ?>" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.