In my opinion, it's a code smell if you're including scripts via GET variables, but you can do this elegantly using a value class with methods whose logic return the value object itself if true.
The idea is to keep in mind that a switch
statement will execute any code where $switch == $case (a loose match). So just create methods which either return $this
, or nothing at all.
Example:
class Haystack {
public $value;
public function __construct($value)
{
$this->value = $value;
}
public function contains($needle):
{
if (strpos($this->value, $needle) !== false)
return $this;
}
}
$kw = new Haystack($_GET['kw']);
switch ($kw) {
case $kw->contains('berlingo'):
require_once 'berlingo.php';
case $kw->contains('c4'):
require_once 'c4.php';
}
You can, of course, generously garnish this code with typehints. If you do, and are not using a version of PHP which supports nullable return types (ie a method signature of public function contains(string $substring): ?Haystack
) then your class would have to elaborate to reflect that.
Example:
final class Haystack {
private $value;
private $isMain;
public function __construct(string $value, bool $isMain = true)
{
$this->value = $value;
$this->isMain = $isMain;
}
final public function contains($needle): Haystack
{
if (strpos($this->value, $needle) !== false)
return $this;
return new Haystack($needle, false);
}
}
This way, if your explicit matching logic fails inside the method, if for some reason new Haystack($_GET['kw']) == new Haystack($needle);
is true, the non-matching property "$isMain" will ensure they are not evaluated as equal.
Again, I would re-examine why you'd want to do this in the first place for this particular situation; traditionally, Composer is a dependency management tool which would be used to include various scripts you need via a PSR autoload standard. That in combination with a Router library would probably be the most useful to address your actual needs.