Search code examples
phpzend-framework2laminas-api-toolszend-framework3

Apigility get Resource name and request method type


how can i get resource name in Apigility ? i tried
$route = $event->getRouteMatch(); but if resource name contain more than name it split it by .

example if reouece name "employeeVerifySomething" it return "employee.verify.something" ?

Also i need to get request type to distinguish between get in "fetch && fetch all "


Solution

  • You can catch them up from in your onBootstratp() method of your module.config.php. Check out the following method

    public function onBootstrap(MvcEvent $e)
    {
        $request = $e->getRequest();
    
        // Get the request method
        $method = $request->getMethod();
    
        // Get the path according to your format
        $path = $request->getUri()->getPath();
        $parts = explode('/', $path);
        if (!empty($parts)) {
            foreach ($parts as $part) {
                $words = preg_split("/((?<=[a-z])(?=[A-Z])|(?=[A-Z][a-z]))/", $part);
                if (!empty($words)) {
                    $words = array_filter($words, function($value, $key){
                        return !empty($value);
                    }, ARRAY_FILTER_USE_BOTH);
                    $words = array_map('strtolower', $words);
                }
                $paths[] = join('.', $words);
            }
        }
    
        // Here is the formatted path
        $path = join("/", $paths);
    
        echo $method; // Outputs the requested method for example, GET
        echo $path; // Outputs employee.verify.something against employeeVerifySomething 
    }
    

    The $path variable of the above method would be able to return the formatted resource that you wanted. For example, "hunkeyPunkey/munkeyDunkeyChunkey" would be outputted as

    /hunkey.punkey/munkey.dunkey.chunkey