如何在Symfony Bundle中包含自定义类?

[英]How to include a custom class in a Symfony Bundle?


I have a Symfony bundle where I will have to use a custom class. This class does not have to be accessible from all the website, but just in a controller of this bundle. I have seen a few solutions relative to the vendors, but this is quite heavy and not necessary in my case. Does someone have a simpler solution?

我有一个Symfony包,我将不得不使用自定义类。此类不必从所有网站访问,而只能在此捆绑包的控制器中访问。我已经看到了一些与供应商相关的解决方案,但这很重,在我的情况下不是必需的。有人有更简单的解决方案吗?

2 个解决方案

#1


5  

Class must be created in Acme\Bundle\Model namespace and folder, not \Class! Who says this?!

必须在Acme \ Bundle \ Model命名空间和文件夹中创建类,而不是\ Class!谁说这个?!

// ../src/Acme/Bundle/Model/Utility.php
<?php namespace Acme\Bundle\Model;
class Utility:
..

Using in controllers:

在控制器中使用:

<?php ..
use Acme\Bundle\Model\Utility;

$x = new Utility(); // FINE!:)

Name of file (Utility.php) must be equal to the class name.

文件名(Utility.php)必须等于类名。

#2


20  

This is what namespaces are for.

这就是命名空间的用途。

From php.net:

来自php.net:

What are namespaces? In the broadest definition namespaces are a way of encapsulating items.

什么是命名空间?在最广泛的定义中,命名空间是一种封装项目的方式。

Simply put, include your namespace at the top of your custom class.

简而言之,将您的命名空间包含在自定义类的顶部。

src/Acme/DemoBundle/Model/MyClass.php

SRC /阿克米/ DemoBundle /型号/ MyClass.php

<?php 
namespace Acme\DemoBundle\Model;

class MyClass { // ...

and use it in your Controller:

并在您的控制器中使用它:

src/Acme/SomeOtherBundle/Controller/DefaultController.php

的src / Acme公司/ SomeOtherBundle /控制器/ DefaultController.php

<?php
namespace Acme\SomeOtherBundle\Controller;

// ...
use Acme\DemoBundle\Model\MyClass; # can be used in any class in any bundle
// ...

class DefaultController extends Controller { // ...

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2013/07/03/b150f3ef50c1197af4b5270e16fb038.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号