0

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?

1
  • The documentation about the service container could be interesting for you. Commented May 13, 2013 at 13:31

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.