I\'m starting to work with Laravel 4, it seems to be a great choice, anyway before coding my first project i\'d like to understand if my usual approach could be ok with lara
Well, let's begin...
First, I created Andreyco\Cart
package using Artisan.
Package and it's structure
|workbench
|-andreyco
|---cart
|-----public
|-----src
|-------Andreyco
|---------Cart
|-------config
|-------lang
|-------migrations
|-------views
|-----tests
|-----vendor
In the answers, I will use this exact package as example.
Imagine, that folder workbench/andreyco/cart/src
is the application folder. If you do, you should know the most of the answers. (Actually App is package as well)
Q: how to setup routes
A: Create the file -> workbench/andreyco/cart/src/routes.php
. This is done.
Q: where to put controllers and models
A: Just create controllers
and models
folder there.
So the TestController
would be located at workbench/andreyco/cart/src/controllers/TestController.php
file. Very same with models.
Directory tree would look like this
|workbench
|-andreyco
|---cart
|-----public
|-----src
|-------Andreyco
|---------Cart
|-------config
|-------controlers
|-------lang
|-------migrations
|-------models
|-------views
|-----tests
|-----vendor
I created the routes.php
, TestController.php
and the TestModel.php
// workbench/andreyco/cart/src/routes.php
<?php
Route::get('test', 'Andreyco\\Cart\\Controllers\\TestController@index');
// workbench/andreyco/cart/src/controllers/TestController.php
<?php namespace Andreyco\Cart\Controllers;
use Andreyco\Cart\Models\TestModel;
class TestController extends \BaseController
{
public function index()
{
return TestModel::printCurrentLocation(__DIR__);
}
}
// workbench/andreyco/cart/src/models/TestModel.php
<?php namespace Andreyco\Cart\Models;
class TestModel extends \Eloquent
{
public static function printCurrentLocation($location)
{
return "Testing package controller, script is located at: {$location}";
}
}
As you can see, I used namespaces, so you should.
Namespaces make your life a lot of easier.
Important: after creating those files, you need to update composer.json
file, so that classes could be autoloaded
// composer.json
"autoload": {
"classmap": [
...
"workbench/andreyco/cart/src/controllers",
"workbench/andreyco/cart/src/models"
]
},
After this, dump the changes using composer dump-autoload -o
command.
Q: So, what's the approach i should follow for keeping things in the laravel way?
A: In my opinion, you should stick to packages. At least, I would. That's the way Laravel was designed to work.
I hope this helps you, good luck!
Edit
Views are not problem here. They work just like in main app package.
// workbench/cart/src/view/foldername/viewname.blade.php
<h1>Testing view file.</h1>
{{ "Blade" }} syntax is parsed as well, no problem here.
Returning view from package's controller is pretty simple
public function index()
{
return \View::make('cart::foldername.viewname');
}