我在哪里将自定义代码放在Laravel中 [英] Where do I put custom code in Laravel

查看:62
本文介绍了我在哪里将自定义代码放在Laravel中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天,

我从以前的非mvc应用程序中获得了一些自定义代码.这都是经过单元测试的东西.现在,我需要将其放入laravel应用程序中.他们不是控制器,还是模型或视图?这是否意味着我必须将它们与Symfony和Swiftmailer文件夹一起放在供应商文件夹中?

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 controllers, or models or views? Does this mean I have to put them in the vendor folder with the Symfony and the Swiftmailer folders?

推荐答案

您是指自定义类吗?有时我将一些类放在单独的目录中,因为正如您所说,它们既不适合模型,视图也不适合于控制器(或routes.php).

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).

我要做的是在app下创建一个名为libraries的新目录.您可以随意命名.然后将其添加到composer.json文件自动加载部分.

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"
}

别忘了从终端或CMD运行composer dump-autoload来更新自动装带器.

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

这将使自定义类自动加载,您可以像这样YourClass::yourfunction($params)

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)

如果您喜欢截屏,我想推荐有关验证的Jeffrey Ways截屏.他创建了一个用于验证模型的自定义类.他还展示了如何在您的应用程序中全局设置自定义类. https://tutsplus.com/lesson/validation-services/

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/

这篇关于我在哪里将自定义代码放在Laravel中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆