Laravel File Structure

Thanks For Sharing :-)Share on Google+Share on FacebookTweet about this on TwitterShare on RedditShare on StumbleUponEmail this to someonePin on PinterestShare on LinkedInDigg thisShare on Tumblr

laravel file structure

When working on applications and websites, we usually follow some type of convention for organizing files and assets that support the site. You might be familiar with how Codeigniter, CakePHP, or your own home grown solutions work. The MVC architecture has been the de facto design standard for some time now. Of course MVC is our Model, View, Controller design pattern that separates Data, Presentation, and Routing apart to make things easier to control. In the past, we would focus on building Fat Models, while keeping the Controllers and Views very skinny. In other words, most of our processing logic got stuffed into a Model, and at times, this can become hard to manage. So how does Laravel handle this? Well, we still have Models, Views, and Controllers in Laravel, but there is a huge degree of flexibility as to how you can organize your projects. The idea is to break apart long rambling logic into small, focused, components and use php namespace and composer autoload to handle the rest. Let’s take a look at an example of how many developers are structuring their projects now.

Start With A Folder in the App Directory

Let’s imagine we are creating a new web application. Where do we begin? We can start by creating a new project in Laravel like so: php laravel.phar new lfs and this will simply create a new Laravel project for us. We chose lfs for Laravel File Structure, but feel free to name yours whatever you like. This will give us a familiar starting point for the project containing
our app, bootstrap, public, and vendor folders. Navigate into the app folder and you’ll see the commands, config, controllers, database, lang, models, start, storage, tests, and views, folders. It is within this app folder where we can place a root directory so to speak, or a domain level container for everything related to your site. This folder would usually be named after your domain, website, or application name. I’ll use Vegibit for this example.

Populate Your Domain Folder

At this point, you have a dedicated folder to hold all of your files that will help power your application. We can think of all the logic you might need for your app and group these things together within their own sub folders here. What we are doing is laying the groundwork for a clean namespace so that autoloading will be easy. For this example we can add folders like Billing, Exceptions, Handlers, Mailers, Repositories, Services, and Utilities. That is a good starting point.

Move Your Models

Optional! This step is optional, but it does seem to be popular at the moment. When we create a new Laravel Application, a model folder is generated to hold all of our Eloquent models. We also get a nice User.php model to get us started with the Laravel Authentication System. What we can do here is take any models that exist in the model folder, and move them to the root of our new domain level folder. So in our case we’ll move User.php into the Vegibit folder. You can even delete the old models folder once this is complete if you like.

Add Your Interfaces and Implementations

Laravel likes to make use of SOLID design principles. The full scope of that is for another episode, but suffice to say, we’ll make use of interfaces and their implementations here. Following this process, we can then create any piece of the application we need. We can start with creating something that can handle our billing. Since these files deal with billing, place them in the Billing folder that we just created above.

  1. Create Your Interface
    The Laravel Interface is a contract that specifies the methods to be used in the implementation of that Interface. Don’t forget to include your namespace! We can create a billing interface just like this:

    BillingInterface.php

  2. Create Your Implementation
    The interface doesn’t actually do anything, it just sets the contract. Now we have to create some code that will actually do the work for us. We’ll imagine we are using Paypal to handle the billing in this app. Again, don’t forget to include your namespace at the top of the file!

    PaypalBilling.php

  3. Update Composer to Autoload
    We need to update our composer.json so that these new classes will load automatically. We’ll use psr-4 in this case. Here is our updated composer.json

    Alert! Note the convention of how psr-4 differs from psr-0. With psr-4 we must include the trailing double backslashes after the Vegibit namespace, in addition to specifying the Vegibit namespace as part of the app folder like so "Vegibit\\": "app/Vegibit" You’ll also note that we deleted models from the classmap. Run composer dump at the command line.

  4. Test the New Code
    We can now add a simple snippet to our routes.php file to test out our new software!

    When we now visit http://localhost/lfs/public/billuser, we can see that our Billing code is working correctly and outputs, “Billing the user with Paypal”

The Laraway

I see what you did there, Laraway instead of Takeaway. With Laravel, instead of trying to force everything into your models, you can create your own dedicated namespace within your app folder. Once you have that in place you can create as many folders as you need to handle all of the various things that your app will need to do. As long as you keep your namespace declarations and the composer.json file configured properly, it will all just work for you. Very cool indeed!

Thank you for reading Laravel File StructurePlease do share using the buttons below!

Thanks For Sharing :-)Share on Google+Share on FacebookTweet about this on TwitterShare on RedditShare on StumbleUponEmail this to someonePin on PinterestShare on LinkedInDigg thisShare on Tumblr

PHP Namespaces Tutorial

Thanks For Sharing :-)Share on Google+Share on FacebookTweet about this on TwitterShare on RedditShare on StumbleUponEmail this to someonePin on PinterestShare on LinkedInDigg thisShare on Tumblr

PHP Namespaces Tutorial

If you come from the C sharp or Java World, namespaces are not a new idea to you. In PHP, it was only once PHP 5.3 was released that namespaces gained official support in the language. Namespaces are changing the way applications in PHP are written, and they are likely one of the most important additions to the language in recent times. In this episode, we’ll take a look at what namespaces are, why they benefit us, and how to use them. Let’s dig in!

What Problems Do Namespaces Solve?

As you began your PHP programming, you likely found that over time as your programs became larger, things started to become cluttered and hard to find. In addition to this, you may have started to add libraries from other developers. Adding more classes and method names to your project starts to become problematic without namespaces because if you have a class or method with the same name, your program will fail. This is called having collisons. With namespaces, we fix the problem of collisions in our codebase. Namespaces support PHP classes, functions, and constants.

PHP Namespace Example

Before namespaces, all PHP code just lived in a global namespace. We can place a piece of PHP code into a namespace by using the namespace command like so:

Any PHP code that comes after this line now lives in the Vegibit namespace. You can also define more than one namespace in the same PHP file like so:

Truth be told, it’s probably a good idea to keep your namespace to one per PHP file. After all, you’re using namespaces to reduce collisions and confusion in the application, no need to complicate things. The above example does highlight nicely the benefit of namespaces however. Notice that both the Google and Bing namespace each have a class named search and a method named query? You can’t do that in the global namespace! Since we declared these classes and methods in different namespaces however, we can use each class and method to our hearts content, with no need to worry about running into collisions.

PHP Namespace Hierarchy

Most times you will see namespaces following the convention of matching a folder structure. By using a backslash character between folder names so to speak, you can define very precise naming conventions for where your libraries and PHP code lives. Maybe you have some code that deals with the Facebook API. You might declare code in that folder like so, namespace Vegibit\Facebook while your database code might be namespace Vegibit\Database\MySQL and common helper methods might use namespace Vegibit\Common\StringHelpers. It is very flexible.

How To Use Namespaced Code

So far we have only looked at how to define namespaces and place code within them. What about when we need to actually make use of that code? Let’s take a look at a namespace example to demonstrate. We’ll create a file named vegilib.php and define a constant, function, and class with the Application\vegilib namespace. Check it out:

vegilib.php

To call this code, we can use PHP just like this:

application.php

Results in:

You’ll note that we had to use the full namespace path in order for this code to run successfully. This is what is referred to as a fully qualified namespace and includes the initial backslash. So what happens if we just put this application code inside the same namespace? Let’s see!

application.php (namespaced)

Awesome! Since we now have the application code living in the same namespace, you can see that instead of having to use the full path in our execution code, we can simply access our constant, function, and class method directly since we are in the same namespace.

Importing Namespaces

As we just saw, you can place your application code into the same namespace as your library, and this will give you direct access to the guts of that library without having to specify the fully qualified namespace. Let’s look at importing namespaces using the use and as keywords, it’s quite slick! We’ll break up our earlier example of the Google and Bing namespaces into separate class files for this example.

google.php

bing.php

If we update our application.php file to the following:

Results in

We’ll now find that we can search Google and Bing using the same Class and Method names, just from another namespace. Make note of both use Google as g; and use Bing as b;. What this says is that we want to use each namespace as something else. So in the case of the Google namespace, we can instantiate an object like this $searchengine = new g\Search; and to instantiate an object in the Bing namespace we can do this $searchengine = new b\Search;

If we omit the lines:

we can still use those classes and methods but we’ll now have to include the full namespace when trying to instantiate an object like this:

Some of this is a matter of preference, while some of this is quite nuanced to the point of if you don’t follow the conventions very specifically, your app will break. When in doubt, hit up the official docs and various definitions and rules to be sure you are following the best practices.

What is __NAMESPACE__ ?

This is a constant that refers to the current namespace. In the global namespace, this constant has no value, or an empty string. Let’s adjust our most recent application code to test this out:

Now what we have here is a snippet of PHP code that lives in the Bing namespace. Within this namespace we import the Google namespace and alias it as the letter g. Therefore, the object creation and method call runs, and we search google. Be echoing out the __NAMESPACE__ constant, we can see that yes, this file does live in the Bing namespace.

So what is this good for? A good question indeed! It turns out you can use this constant for debugging purposes as well as to create dynamically generated fully qualified class names.

Namespaces and Autoloading

Namespaces are going to be key for you to use autoloading in your PHP projects moving forward. Like we mentioned in this Composer Autoload Tutorial, Composer makes heavy use of Namespaces in order for it to work it’s magic. By learning your Namespaces as well as your psr-0 and psr-4 standards, you will be well equipped to deal with the new methods of PHP workflow.

Thank you for reading PHP Namespaces TutorialPlease do share using the buttons below!

Thanks For Sharing :-)Share on Google+Share on FacebookTweet about this on TwitterShare on RedditShare on StumbleUponEmail this to someonePin on PinterestShare on LinkedInDigg thisShare on Tumblr