dourao1877
2013-05-13 10:32
浏览 25
已采纳

如何在symfony2中访问自定义类?

I have created a custom class with few method in it. e.g.

 class MyClass{

  method1 ();

  method2();
}

Now I want to create object of this class and use it inside a controller method

class DefaultController{

public function myAction()
{
  //here I want to able to create object of MyClass, is it possible? 
}

}

Q1. where should I store this class in symfony2 structuere e.g. inside src dir?

Q2. How can I use this class method inside the controller of a bundle?

图片转代码服务由CSDN问答提供 功能建议

我创建了一个自定义类,其中包含很少的方法。 例如

  class MyClass {
 
 method1(); 
 
 method2(); 
} 
   
 \  n 

现在我想创建这个类的对象并在控制器方法中使用它

类DefaultController {

  public function  myAction()
 {
 //这里我希望能够创建MyClass的对象,这可能吗?  \ N} 
   
 
 

}

Q1。 我应该在symfony2结构中存储这个类,例如 在src dir里面?

Q2。 如何在bundle的控制器中使用此类方法?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongqiong8021 2013-05-13 10:39
    已采纳

    If you put your class in the src folder, it will be autoloaded, ie: you can simply do:

    $foo = new \MyClass();
    $foo->method1();
    

    in your Controller.

    A good approach would be to put your classes in the Bundle you are likely to use them:

    src/YourCompany/YourBundle/MyClass.php
    

    In this way however don't forget to put the namespace declaration on top of your MyClass file:

    namespace YourCompany\YourBundle;
    class MyClass{
       //..
    }
    

    You can put your classes on the base folder of your bundle, or use other nested folders to better differentiate a set of classes from each others, for eg:

    src/YourCompany/YourBundle/Listener/MyClassListener.php
    src/YourCompany/YourBundle/Manager/MyClassManager.php
    

    For more info see the Best practice on Bundles structure of Symfony2

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题