Where do I put custom code in Laravel

后端 未结 2 965
失恋的感觉
失恋的感觉 2021-01-13 02:57

Good day,

I have some custom code from a previous non-mvc application. It\'a all unit tested and stuff. Now, I need to put it in a laravel application. They are not

相关标签:
2条回答
  • 2021-01-13 03:18

    You should also add the path to /start/global.php

    There is a more complete answer here:
    What are the best practices and best places for laravel 4 helpers or basic functions?

    0 讨论(0)
  • 2021-01-13 03:38

    Do you mean custom classes? Sometimes I put some of my classes in a separate directory, because as you said, they wouldn't fit in either the model, view or controller (or the routes.php).

    What I did was to create a new directory under app called libraries. You could name it whatever you want. Then you add it to the composer.json file autoload portion.

    {
        "require": {
            "laravel/framework": "4.0.*",
        },
        "autoload": {
            "classmap": [
                "app/commands",
                "app/controllers",
                "app/models",
                "app/database/migrations",
                "app/database/seeds",
                "app/tests/TestCase.php",
                "app/libraries" // <---Added here
            ]
        },
        "scripts": {
            "pre-update-cmd": [
                "php artisan clear-compiled"
            ],
            "post-install-cmd": [
                "php artisan optimize"
            ],
            "post-update-cmd": [
                "php artisan optimize"
            ]
        },
        "config": {
            "preferred-install": "dist"
        },
        "minimum-stability": "dev"
    }
    

    Dont forget to run composer dump-autoload from your terminal or CMD to update your autoloader.

    This will make the custom class autoload and you can use it where ever you want in your project by calling it like so YourClass::yourfunction($params)

    If you prefer a screencast I would like to recommend Jeffrey Ways screencast about validation. He creates a custom class for validating a model. He also shows how to setup a custom class globally in your app. https://tutsplus.com/lesson/validation-services/

    0 讨论(0)
提交回复
热议问题