I have been going back and forth on this subject and could really use some insight.
I am writing an API in Laravel and an Web App in Laravel. I have been going back and forth in this process wondering if they should be in the same Laravel install or if they should be in separate installs. The pro's and con's I can think of for separate installs are as follows:
Pro's
api code doesn't interfere with web code
would use API for
data fetching and updating -> might be good for future scaling
Con's
Multiple laravel installations
Unable to use Eloquent (would save a
lot of work) -> since data would come from api.
What is the best way to do this?
Also, the real question is, if I were to keep them on the same installation, what is the best way to set up the folder structure to essentially run to apps on a single Laravel installation?
You can separate the code with namespaces. Use the composer.json file and PSR-4 so you can have separate code bases, even controller and models. Or you can use the same models in the Core namespace.
{
...
"autoload": {
"psr-4": {
"Api\\": "app/Api",
"Core\\": "app/Core",
"Web\\": "app/Web"
},
...
}
Surely you would want to keep the models together at least?
I recommend keeping the installs together and separating using routes:
Route::group( array('before'=>array('api'), 'prefix' => 'api' ), function() {
...
}
Route::group( array('before'=>array('auth'), 'prefix' => 'webapp' ), function() {
...
}
Structure is personal preference but I would have:
Controllers
|------API
| |-------MyController.php
|
|------WebApp
|-------MyController.php
And then in the controller use namespaces:
<?php
namespace API;
class MyController extends \APIBaseController {
Update:
If you want namespaces throughout then do this:
app
|
|------core
| |-------Models
|
|------api
| |-------Controllers
|
|------webapp
|-------Controllers
Related
This may be a dumb question, but I've started exploring Laravel Breeze with vue and I'm not sure how to manage resources and their views. (Using Laravel 9)
For example, if I have a table 'members' and a resource controller 'MemberController', ordinarily in the web.php file I would do something like:
Route::resource('members', MemberController::class)->names('members');
Then I'd create a 'member' folder in my resource/views folder to store the views for that table. I could then call the view from the MemberController something like:
public function index()
{
$members = Member::all();
return view('member.index', compact('members'));
}
I'm trying to do something similar using vue in breeze, so I guess I'd have the vue pages in the 'resources/js/Pages' folder. But this didn't seem to work properly.
I don't know how to transition from the previous approach of handling resources and views to Breeze using vue.
What's the recommended way to handle resources in an SPA with Breeze/vue?
After following Djave's suggestion, I took a look at the sample app from inertia.js and that answered everything.
The problem I had was due to using the dot notation when specifying the path to the vue page. So, in my example above, it should instead be like this:
return view('Member/Index', compact('members'));
The inertia sample app code has a lot of good examples!
On the documentation for Slim Framework, it says
In this example application, all the routes are in index.php but in
practice this can make for a rather long and unwieldy file! It’s fine
to refactor your application to put routes into a different file or
files, or just register a set of routes with callbacks that are
actually declared elsewhere.
It doesn't say how to actually do this though. My only thought is that you could split code into multiple PHP files and then use include or require in index.php to reference these.
I'm also not sure what it means by "register a set of routes with callbacks that are actually declared elsewhere"
Does anyone have any thoughts on this, since the application I'm wanting to build might have quite a few routes?
Being a micro-framework, Slim does not enforce any specific method. You can either find a ready-to-use structure (Slim Skeleton Application comes to my mind) or write your own; unlike other frameworks, Slim does not try to protect you from PHP.
Route definitions can be something as simple as an array of strings:
<?php // routes.php
return [
'/' => ['Foo\\Home', 'index'],
'/about' => ['Foo\\Home', 'about'],
'/contact' => ['Foo\\Contact', 'form' ],
];
... which you then load and process in your index.php entry point:
$routes = require('/path/to/routes.php');
foreach ($routes as list($path, $handler)) {
$app->get($route, $handler);
}
And you can leverage the existing Composer set up to auto-load your classes by adding the appropriate directories to composer.json:
{
"require": {
"slim/slim": "^3.3",
"monolog/monolog": "^1.19"
},
"autoload": {
"psr-4": {"Foo\\": "./Foo/"}
}
}
From here, it can get as complex as required: define routes in a YAML file, auto-load from defined classes, etc.
(Code samples are shown for illustration purposes and might not even be valid.)
There're some thoughts on it in Slim documentation
Instead of require's you can use composer autoloading
"register a set of routes with callbacks that are actually declared elsewhere"
From docs:
Each routing method described above accepts a callback routine as its final argument. This argument can be any PHP callable...
So you can do:
$routeHandler = function ($request, $response) { echo 'My very cool handler'; };
$app->get('/my-very-cool-path', $routeHandler);
But usually people use classes instead of functions:
http://www.slimframework.com/docs/objects/router.html#container-resolution
I think you almost get the basic idea right. I recommend reading chapter on routing a couple of times. It covers everything pretty good.
Happy coding and let me know if you need any other help!
I have some php lines which will be used very often in my application. So I would like to build a function and call it every where in my app. My function could be :
static function array_matiere($id_ecole) {
return $something;
}
I tried to put this code in a controller and then call it like that :
$liste_matieres = MatieresController::array_matieres(Session::get('id_ecole'));
It works, but where to put this kind of function ? in the controller ? in a method file ? what is the best practice ?
Thanks for your responses.
Dominique
There are multiple ways to implement this. look here
Method 1 This method is highly suggested by Laravel Expert ( JeffreyWay)
If your helper functions are similar to the way laravel 5 ones work, i.e Illuminate/Support/helpers.php you could just create a helpers.php and have composer do the autoloading for you.
Edit your composer.json file and add the file to the autoloading key. In my example my app is called Tasky so just add the files key and reference helpers.php.
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"Tasky\\": "app/"
},
"files": [
"app/Support/helpers.php"
]
},
That way you just create your file inside app/Support/helpers.php and all your common function based view helpers or other helpers can go here. If you take the class based approach then the above is great.
Also then remember to just run the following once.
$ composer dumpautoload
Source
Method 2
Please Follow the link and read answer & Its comments
Whenever u need to include a piece of code providing some functionality through out your application then the best way in Laravel is to make Service class inside app/Services and then you can use that class anywhere in your application using
use App\Services\YourServiceName;
I'm new in laravel, I wants to make separate folder for admin & front end. I've made folder like this
app/http/Controllers/Catalog/Common/home.php
app/http/Controllers/Admiin/Common/home.php
I wants to place common controllers in common folder like header, footer etc. In any another folder will be another related files like eg: category
app/http/Controllers/Catalog/Category/list.php
app/http/Controllers/Catalog/Category/product.php
app/http/Controllers/Admiin/Category/list.php
app/http/Controllers/Admiin/Category/categoryForm.php
But I'm stuck to make it working with routes, Should I use the same logic in Laravel or is there a better way to do it? Please suggest me how can I do it?
Here are the first four lines of my home controller
namespace LocalProject\Http\Controllers\Catalog\Common;
use Illuminate\Http\Request;
use LocalProject\Http\Requests;
use LocalProject\Http\Controllers\Controller;
I'd really appreciate any kind of help.
Routes work based off of namespaces, class names, and functions.
\Namespace\Classname#functionName
Folder structure shouldn't matter.
Edit for some more question specific answers:
You probably want to use something like this:
Route::get("home/index", [ "as" => "home.index", "uses" => "\LocalProject\Http\Controllers\Catalog\Common\HomeController" => "HomeController#index" ]);
You may also want to look into Route::group to help keep your namespaces more organized.
I wrote a REST API with Laravel. On top of that i want to create an admin panel with a lot of statistics and "mighty" moderation tools which should render on server-side.
While the REST API uses OAuth2.0 and only returns JSON+HAL (HATEOAS), the admin panel would use a HTTP Basic auth plus a normal credential login with session based authentication.
I know it would be easily possible to use a second auth-filter and Route groups to make all this happening in one application. And i know that libs are only loaded if needed. But i want to create a second application which is completely independent.
Why?
To keep the REST API lightweight: No unnecessary libraries, no second auth-layer, no additional routes, rules and filters, etc. The REST API is Restful and i do not want to add additional clutter. Though it might make testing a little bit more complicated.
Here is how it should look like:
backend
rest (Laravel application 1)
-- app
--- models
---- RestapiModel.php
admin (Laravel application 2)
-- app
--- models
---- AdminModel.php
The problem is: In application 2 i need to work with models of application 1
So i would like to do s.th. like
class AdminModel extends RestapiModel {
protected $connection = 'application_1_database';
// Statistical methods
// Database manipulation
// etc.
}
I now have two questions:
How can i make this possible? "AdminModel extends RestapiModel" won't work. Do i have to use namespaces, traits or just include the Model on top of the file? How would you solve this?
What do you think about the complete approach to separate API and administration?
Thanks in advance
Phil
It's not pretty but you can use require to import the file(s)
require base_path().`/../rest/models/RestapiModel.php`;
class AdminModel extends RestapiModel {
protected $connection = 'application_1_database';
// Statistical methods
// Database manipulation
// etc.
}
Or you can autload all the models of the rest api using composer. Your composer.json in the admin application could look like this:
// ...
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"../../rest/app/models",
"app/database/migrations",
// ...
]
},
// ...
(After changing the autoload section make sure to run composer dump-autoload)