Fork me on GitHub

Bem vindo

Disclaimer: Majority of the assets, design and format of this site is borrowed (forked might be the more better term) from the original PHP : The Right Way site. The original contributors is given all the credits due to them.

This site serves as a guide for those who is using Laravel Framework by Taylor Otwell and its contributors. Laravel : Best Practices aims to put together all the resources and best practices in using the Laravel Framework.

Laravel Framework is not strict on how and where you define your classes as long as it could be loaded by Composer. This is a double-sided blade – it’s beneficial for advanced developers, but coud be confusing for beginners and for those who is trying to reverse engineer an existing codebase. The ability to place anything, anywhere is good. But there are times some methods is way better than the others, and that is what we are after. This site tried to collect all the best practices, tools and methodologies, so that it could serve a guide for beginners and existing developers alike.

This is a living document and will continue to be updated with more helpful information and examples as they become available.

Traduções

Laravel: The Best Practices is currently available in the following languages. Please contribute to the project so that it could support multiple languages.

How to Contribute

Help make this website the best resource for new PHP programmers! Contribute on GitHub

Spread the Word!

Laravel Best Practices has web banner images you can use on your website. Show your support, and let new PHP developers know where to find good information!

See Banner Images

Download the Android Application

Get it in Google Play

Back to Top

Começando

O ecossistema

At the very minimum, you need to know how to use Git and Composer. Though not required, it is better that you have an account on GitHub.com as it is where all the code and its’ dependencies are hosted.

For local development, you’ll need to have at least Vagrant and VirtualBox installed. This is used by Homestead (a special vagrant box made for running Laravel apps). Although you can use the traditional WAMP/MAMP/XAMPP stack, those are not officially supported, thus you might have hard time down the road.

Pure “Laravel-way” frontend development might be a daunting one as it got has a long chain of technologies. At the very top of the chain is Elixir, which is basically an API for GulpJS, which in turn requires npm which is basically a package manager for NodeJS.

CSS is managed either through Sass or LESS, while JavaScript is through CoffeeScript. You can write ES6/ES7 code since Elixir also supports BabelJS. While NodeJS dependencies are then made available to browsers through Browserify.

For the backend stack, at the very least, you need a web server like Nginx, a php interpreter like PHP-FPM and a database like MySQL. Other optional stack components are Memcached, Redis and Beanstalkd.

While you are not required to understand them all at once, it is advantagous that you are at least familiar with these and do some reading about what they are and where they are being used. This will save you tons of confusion when reading the documentation and references in the future.

Use a versão estável (5.4)

If you are getting started with Laravel, start with the current stable release of Laravel 5.4. Laravel has added powerful new features over the last few years. If you are looking for a function or its usage, the documentation on the laravel.com/docs website will have the answer.

Homestead

Laravel is not only using Vagrant as the official development environment but also has its own base box called “Homestead”. You can use Homestead to start developing with Laravel without the hassle of setting up your local environment for Laravel.

The instructions and usage of homestead can be found in the Official Documentation.

Construa o seu próprio Homestead

Homestead comes with pre-installed software. If you want to customize the installed software, you will need to have access to the scripts that is used to build Homestead itself. This project is called “Settler”. You can check the source code of that project to have a better understanding of how Homestead was built, and probably add your own scripts as well.

Back to Top

Guia de estilo de código

O Laravel sozinho não impõe nenhum estilo de código, ou como nomear variáveis e muito menos onde armazenar os seus arquivos. Com tanto que o Composer conseguir carregar os arquivos, o código irá ser executado normalmente. Entretando programadores devem estudar e seguir os padrões PSR:

Back to Top

Destaques

Paradigmas de programação

Design Patterns (Padrões de projetos)

Existem diversos padrões de projetos que são utilizados no Laravel. Phill tem uma palestra muito boa sobre o assunto.

Como o Laravel funciona?

Christopher Pitt explica como o Laravel funciona. você pode ver isso no link http://rebuildinglaravel.com/

Eloquent ORM

Uma das características mais populares do Laravel é o seu ORM Eloquent. É a maneira mais fácil de usar um ORM na sua aplicação. Você pode ler mais sobre o Eloquent na documentação oficial.

Linha de comando

Laravel possui uma ferramenta para interagir com a linha de comando chamada Artisan. Essa ferramenta usa o console do Symfony como base. Laracast posui um tutorial prático para aprender como criar seus próprios comandos.

Debugging

Laravel é conhecido pela sua página de error personalizada, graças a biblioteca Whoops que torna isso possível.

Back to Top

Gerencimento de dependências

Laravel is not built from scratch. It is built on top of several frameworks and libraries. You can see the list of other libraries it uses here. It is also powered by Illuminate components. All of these components are combined by making sure each of them can be treated and written as a composer Composer library. These libraries are hosted in public repositories.

Composer e Packagist

By default, Packagist is used as a package repository and GitHub to download the files itself. But you can define your own repositories by setting up your own Satis mirror of packages. Although you can use any class or even plain php functions inside Laravel (as long as it can be autoloaded). This is not a recommended practice. Make your own Composer library for each application specific set of classes and include it as a dependency in the composer.json file.

Laravel Package Archivists

These are the sites where you can find Laravel Packages:

Back to Top

Práticas de código

O básico

Laravel possui milhões de funcionalidades que parecem sem fim.

Veja alguns artigos e fontes que podem ser ajudar a entender o mundo do Laravel.

Date and Time

PHP possui uma classe chamada DateTime para nos ajudar a ler, escrever, comparar ou cacalcular datas. Mas com Laravel é recomendado que se use a biblioteca Carbon para executar essas operações.

Design Patterns

It is easy to mess up your Laravel application if you don’t have any sort of pattern to follow. The following design patterns are recommended for those who are building an application with Laravel or want to refactor their existing projects:

Working with UTF-8

Laravel utiliza a biblioteca patchwork/utf8 para tratar questões relacionadas ao UTF8. Caso você não entenda sobre UTF8 veja os links a seguir

Back to Top

Convensões de banco de dados

Eloquent suporta multiplos bancos de dados por um motivo - Não se limite a usar somente MySQL.

Use MongoDB for records that have attributes that vary a lot. For example, in an inventory system, an office supplies product might have a different set of fields compared to vehicle and auto supplies.

Use ElasticSearch for high volume data searching and indexing.

Use Neo4J for applications that require complex relationships between models. For example a multi-level networking application, social network site and similar apps.

Tabelas e nomenclatura de campos

Table and field names MUST be lowercase and use Snake Case.

Table names should use the plural form of the actual real life object it is storing. Like for example, the table name for blog posts should be posts not post.

Primary keys should be named “id” in the table names. While the foreign key it represents in other table should be on singularform_id. (e.g. table: post, primary key: id, foreign key: post_id )

Alterando tabelas, índice ou inserindo dados.

DON’T create tables or index directly via PHPMyAdmin or console. Use database migration to create table, add/alter any fields, and commit those to Git repository.

DON’T directly pass the database export (sql files) to your colleagues in order to share your database changes. Let them run the migration files you committed to the repository.

DON’T insert fake values directly into the database for testing purposes. Create Seeder files to populate your database.

Escolha o banco de dados correto.

Eloquent dá suporte a múltiplos banco de dados por uma razão - não se limite a usar somente MySQL.

Use MongoDB for records that have attributes that vary a lot. For example, in an inventory system, an office supplies product might have a different set of fields compared to vehicle and auto supplies.

Use ElasticSearch for high volume data searching and indexing. It is also useful on systems that requires sharding of data across multiple machines which is very huge to fit in a single replica.

Use Neo4J for applications that requires complex relationships between models. For example a multi-level networking application, social network site and alike. Although you can do the same in MySQL, the amount of joins when you go beyond 2-level parent-child relationships will be unbearable in any production environment.

Back to Top

Configurações

Sempre tenha certeza que a chave da sua aplicação está configurada. A chave é definida na constante APP_KEY no arquivo .env. Você pode gerar uma automaticamente com o comando:

php artisan key:generate

Sempre defina o nome da sua aplicação. Ou seja, em vez de utilizar o namespace padrão App, defina um namespace que faça sentido para a aplicação. Isso pode ser feito através do comando:

php artisan app:name NomeDaSuaAplicacao

Isso faz com que os controllers/models usem o namespace NomeDaSuaAplicacao\Controllers e NomeDaSuaAplicacao\Models.

Use o arquivo .env para armazenar qualquer informação importante e acesse esses valores através da função getenv. Não use os seus models/controllers para armazenar essas informações e commita-las no Git.

Back to Top

Fontes

Documentos oficiais

Pessoas a se seguir

Mentoria

PHP PaaS(Platform as a service - Plataforma como serviço)

Componentes

Componentes Illuminate podem ser encontrados em https://github.com/illuminate

e são a menor parte que compõe o Laravel Framework. Muitas outras bibliotecas open-source são usadas pelo Laravel, basta ver o arquivo composer.json para encontra-las https://github.com/laravel/framework/blob/5.0/composer.json#L22-L43

Outras fontes interessantes

Laracasts

Projetos criados com Laravel

Canais do YouTube

Videos pagos

Livros

Back to Top

Comunidades

Grupo de usuários

Eventos

Back to Top