ReynierPM
ReynierPM

Reputation: 18680

How to call a function outside controller folder and without routes?

I have the following StringTools class defined under Clanmovil\PlatformBundle\Tools namespace:

namespace Clanmovil\PlatformBundle\Tools;

class StringTools
{
    /**
     * Generate as many unique permutations of letters for a given word
     * @param string $input
     * @return array
     */
    public static function permutationWords($input)
    {
        $input = strtolower($input);
        $results = [];
        $length = strlen($input);
        $counter = pow(2, $length);

        for($i=0; $i<$counter; $i++) {
            $binaryStr = str_pad(decbin($i), $length, '0', STR_PAD_LEFT);

            $variant = '';
            for($j=0; $j<$length; $j++) {
                $variant .= ($binaryStr[$j] == '1') ? strtoupper($input[$j]) : $input[$j];
            }
            $results[] = $variant;
        }

        return $results;
    }
}

Now I want to use the output of that function lets said by a call made through AJAX, what will be the right way:

Upvotes: 2

Views: 610

Answers (1)

Richard
Richard

Reputation: 4129

Well you could get that done with almost no controller code, and a controller is designed for web requests, so it's the best option. With barely any code:

use Clanmovil\PlatformBundle\Tools\StringTools;

public function someAction (Request $request) {

    // this could be a JSON response etc
    return new Response(StringTools::permutationWords($request->get('someParam')));
}

Upvotes: 2

Related Questions