Vinee
Vinee

Reputation: 1654

how to create custom or helper function in symfony2 like codeigniter? And where should i keep?

Can i create helper function like codeigniter in symfony2?

I want one function which should print array inside pre tag like

public function print_in_pre_tag($array) {
    echo "<pre>";
    print_r($array);
    echo "</pre>";    
}

I often print array like in that format to check the values.

Please suggest some solution and let me know where can i keep the function?

Edit 1: If i call like print_in_pre_tag($array); inside any controller
above function should invoke.

Upvotes: 1

Views: 4103

Answers (4)

Slashhh
Slashhh

Reputation: 180

Actually, the question is too old to answer, and actually my answer is not about a Helper, it is about the function that you need. You need a pretty var_dump().

From Symfony 2.6, we have the VarDumper Component. You can use it wherever you need, whenever you need, in your php code, of course.

You have to use the function dump(). You can see the dump in the Developer Bar, and also in a redirection page. The output of the dump, it is better formated, because you have arrows to expand all the inners arrays.

Just to let you know guys

Upvotes: 0

Actually, I do not understand why people recommend Services. Services have to contains business logic. For you task use Helpers. They are static, and you do not need instance!

Upvotes: 1

COil
COil

Reputation: 7606

You should use the LadybugBundle which exactly does what you want. It's much more easier to use as you can debug with calls like:

ld($array);
ldd($array);

Moreover, those helpers are available anywhere in your PHP code without requesting or defining a service. Finally it also works to debug in the console, Ajax calls, Twig templates...

Upvotes: 0

Baba Yaga
Baba Yaga

Reputation: 1819

You should create a service (helper in codeIgniter) for that.

Create a folder called Services in your bundle. Create a file in that folder called "PrintManager.php" (or however you want to call it - but make sure the first is capital)

Then inside PrintManager.php you put:

namespace Company\MyBundle\Services;

class PrintManager {

public function print_in_pre_tag($array) {
    echo "<pre>";
    print_r($array);
    echo "</pre>";    
} }

Then in your services.yml you set the file:

parameters: print_manager.class: Company\MyBundle\Services\PrintManager (notice, no .php extension)

services: print_manager: class: "%print_manager.class%"

And then in your controller you can just call it like this:

$printManager = $this->get('print_manager');

$printManager->print_in_pre_tag($array);

Btw the best thing you can do is let your service handle the functional part and let it return the result to your controller and from there you work with the results.

like: $text = $printManager->print_in_pre_tag($array);

Upvotes: 8

Related Questions