Laravel is dependent on MVC design pattern:
In this article we will focus on the most four important partitions of any Laravel project in my opinion.
1- Migrations
In this part we create database tables, we should name their classes in small letters separated by underscore like this=> create_users_table.
2-Model
In this part we create the models of database tables, classes in this part should start with capital letter and be indicated of table name but in a single way for example if we have users table the model of it must be named User.
3-Controllers
in this part we make integration between the model and the view part, classes names in this part start with capital letter and if it consists of more than one word it should be written in camel case like this=> HomeController.
variables and functions names should be meaningful and start with small letter, if it consists of more than one word, start the second word with capital letter.
function should do one thing , its name describe what it do and contains 20 lines of code at most.
function arguments should not be more than two except that we do for example.[1]
class MenuConfig
{
public $title;
public $body;
public $buttonText;
public $cancellable = false;
}
$config = new MenuConfig();
$config->title = 'Foo';
$config->body = 'Bar';
$config->buttonText = 'Baz';
$config->cancellable = true;
function createMenu(MenuConfig $config): void
{// }
-If we have queries needed to be use more than one time in our controller we should create a repository class for it.
and inject an instance of that class into the function or constructor.
-To pass data from our controller to view we use compact () and determine the name of targeted view.
-in case of modify database table in our controller to store data or update it, our controller should contain the names of table columns to avoid conflicts.
-avoid nesting loop too deeply.[2]
-Using single quotes instead of double quotes[2].
4-the View
-Views names should be start with small letters separated by underscore like this=>create_category.
-If we use CSS in our view it should be separated into stylesheet file, added into public partition and call it in our view.
-If we have repeated part in our views like footer, header or error we add this part in separated file and call this file by @include ().
-If we use JavaScript in our view and need to pass repeated html tags to JavaScript function it preferable that create function in our controller.
which return needed html tags to the JavaScript function.
-If we have to iterate data from our controller to be viewed, we should make a simple and understandable integration between PHP and HTML tags.
-avoid writing html tags in php tags .[2]
<? php
echo ‘
Hello
’;
?>
References
Reference[1]: https://github.com/jupeter/clean-code-php#function-arguments-2-or-fewer-ideally.
Reference[2]: https://www.macronimous.com/resources/writing-clean-secure-and-easy-php.asp.