我想創建一個服務,它會做到這一點
創建服務
這樣做的主要職責:
從控制器,你可以得到相同的方式完整路徑類,是得到任何捆綁的默認網絡路徑爲任何資源。
如assets:install
命令定義,對於每個束的相對路徑預期是/bundles/foobar/
對於給定的FooBarBundle
的Acme \ FooBundle \ WebPathResolver
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
class WebPathResolver
{
/**
* Gets the prefix of the asset with the given bundle
*
* @param BundleInterface $bundle Bundle to fetch in
*
* @throws \InvalidArgumentException
* @return string Prefix
*/
public function getPrefix(BundleInterface $bundle)
{
if (!is_dir($bundle->getPath().'/Resources/public')) {
throw new \InvalidArgumentException(sprintf(
'Bundle %s does not have Resources/public folder',
$bundle->getName()
));
}
return sprintf(
'/bundles/%s',
preg_replace('/bundle$/', '', strtolower($bundle->getName()))
);
}
/**
* Get path
*
* @param BundleInterface $bundle Bundle to fetch in
* @param string $type Which folder to fetch in (image, css..)
* @param string $resource Resource (image1.png)
*
* @return string Resolved path
*/
public function getPath(BundleInterface $bundle, $type, $resource)
{
$prefix = $this->getPrefix($bundle);
return sprintf('%s/%s/%s', $prefix, $type, $resource);
}
}
聲明它在你service.yml
沒什麼特別的,但是通常的服務
@ AcmeFooBundle /資源/配置/ services.yml
services:
acme_foo.webpath_resolver:
class: Acme\FooBundle\WebPathResolver
使用
然後你可以用它在你的控制器這樣
的Acme \ FooBundle \控制器\ BarController :: bazAction
$bundle = $this->get('http_kernel')->getBundle('AcmeFooBundle');
$path = $this->get('acme.webpath_resolver')->getPath($bundle, 'image', 'foo.png');
echo $path; // Outputs /bundles/acmefoo/image/foo.png
嘗試修剪成數組的段。然後用它與數組索引。 – ankur140290