简体   繁体   English

Slim框架在路由中共享代码

[英]Slim framework shared code in routes

I have a route group with 6 routes inside it. 我有一个包含6条路线的路线组。 I check the parameters on every route against the database. 我对照数据库检查每条路由上的参数。

What's the best way to achieve this? 实现此目标的最佳方法是什么? Build a class for it? 建立一个班吗?

When working with a database, it really depends on how much you will be using it. 使用数据库时,实际上取决于您将使用多少数据库。 Slim has no database integration, so you could access the database by either using basic php or using a ORM tool to assist you in talking with your database. Slim没有数据库集成,因此您可以使用基本的php或ORM工具来访问数据库,以帮助您与数据库进行对话。

One orm that is quick and easy to use is idiorm http://idiorm.readthedocs.org/en/latest/index.html idiorm是一种快速且易于使用的Orm,网址为idiorm http://idiorm.readthedocs.org/en/latest/index.html

There are other more robust things out there and it all depends on what you are trying to accomplish. 还有其他更强大的功能,所有这些都取决于您要完成的工作。 Really, to give a "best" solution, we would need more information on the situation and also how you would quantify "best." 的确,要提供“最佳”解决方案,我们将需要有关情况以及如何量化“最佳”的更多信息。

Try use Slim Middleware . 尝试使用Slim 中间件

Add your check part as one middleware, and share a middleware for all routes. 将您的支票零件添加为一个中间件,并为所有路由共享一个中间件。 Then you will be happy. 那你会很高兴的。

Depending on your needs, you can also try using class instances as route callbacks. 根据您的需要,您还可以尝试将类实例用作路由回调。

Define a base class with all the database functionality and use "Class Controllers" available since version 2.4.0 (November 2013). 定义具有所有数据库功能的基类,并使用自2.4.0版(2013年11月)以来可用的“类控制器”。

class Base  {
    // Define all your shared DB methods and properties here
}

Use child classes of your base class as controller class instances, as callbacks for your Slim app routes (and their parameters): 将基类的子类用作控制器类实例,用作Slim应用程序路由(及其参数)的回调:

$app->get('/user/:id/', '\Base\User:find');

Getting an instance of $app in the callback class instance is easy enough: 在回调类实例中获取$ app实例很容易:

class User extends \Base {
    public function find($theUserId) {
        // ...
        // You can easily get access to $app here, too:
        // $app = \Slim\Slim::getInstance();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM