Reserved keyword in controller action - Magento 2
-
30-09-2020 - |
Question
I am working on an admin grid concept. I found one github source code and analyzed that one.
While I found the URL is different from the declaration in the UI component layout.
<item name="url" xsi:type="string">*/*/new</item>
*/*
is mean current frontname and action path, but I could not find New.php
in controller path but instead NewAction.php
file is present.
So I am confused. How is this automatically mapping to NewAction.php
like factory method in Model?
can anyone explain this?
Solution
There are some words that you cannot use for class names.
Basically the reserved php words like new
, public
, static
, ...
To overcome this and still allow these words in the urls Magento adds the suffix Action
when the class is autoloaded.
This means that new
maps to NewAction.php
, public
to PublicAction.php
.
You can find in the class \Magento\Framework\App\Router\ActionList
(2.3 branch) the list of words that have this behavior.
protected $reservedWords = [
'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const',
'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare',
'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final',
'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'instanceof',
'insteadof','interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected',
'public', 'require', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var',
'while', 'xor',
];
and here is the code that changes new
to NewAction
.