1

I need to find certain cues in a string and call functions with these cues

Example

<?php
namespace App\Http\Controllers;
class ModulesController
{
    private $modules = [ ['name' => 'someFunction','maxNumber' => 50] ];
    public function checkFunctions($strings = NULL)
    {
     $moduleArrayId = array_search($strings ,array_column($this->modules, 'name');
     if($moduleArrayId !== FALSE)
         $this->$modules[$moduleArrayId]['name'];

    }

    public  function someFunction()
    {
       return "it works";
    }
}

And resource example

<?php
namespace App\Http\Controllers;
use App\Http\Controllers\ModulesController;

class BlockController extends Controller
{
  public function __construct()
  {
     $this->middleware('auth:members');
  }

  public function index(Request $request)
  {
     $string = "someFunction";
     $callBack = new ModulesController;
     var_dump($callBack->checkFunctions($string)); //Always its NULL
  }
}

I have to use this code like this. If I can understand this, I will try to improve it.

2 Answers 2

1

you missed ) in

$moduleArrayId = array_search($strings ,array_column($this->modules, 'name'));

That's why you are getting default value NULL all the time.

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

2 Comments

No, there is no connection.
you haven't returned any value
0

Try this:

public function checkFunctions($strings = NULL)
{
    $moduleArrayId = array_search($strings ,array_column($this->modules, 'name'));
    if($moduleArrayId !== FALSE) {
        $method = $this->modules[$moduleArrayId]['name'];
        return $this->$method();
    }
}

Not sure how much you changed your code in order to post here, but I would suggest you to:

  • Use better names.
  • Do not instantiate/call directly a controller from other controller. Controllers should only be used to handle requests, everything else should be moved to a separate class.
  • Modify the structure of $modules to an associative array, so you can check if the method is defined by index, instead of using array_search. This can make your code run much faster as the size of this structure grows.

Example: 

private $modules = [
    'someFunction' => [
        'maxNumber' => 50
    ]
];

// and then to check if the method is defined:
if (isset($this->modules[$strings])) {
    // ...
}

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.