【发布时间】:2017-01-23 00:30:16
【问题描述】:
我想将中间件添加到我的 Slim 项目中,以在允许用户访问之前检查用户的 ip。
我的中间件类:
<?php
namespace App\Middleware;
Class IpFilter
{
protected $request_ip;
protected $allowed_ip;
public function __construct($allowedip = array('127.0.0.1'))
{
$this->request_ip = app()->request()->getIp();
$this->allowed_ip = $allowedip;
}
public function call()
{
$checkit = checkIp();
$this->next->call();
}
protected function checkIp()
{
if (!in_array($this->request_ip, $this->allowed_ip))
$app->halt(403);
}
}
我的引导索引.php:
<?php
// To help the built-in PHP dev server, check if the request was actually for
// something which should probably be served as a static file
if (PHP_SAPI === 'cli-server' && $_SERVER['SCRIPT_FILENAME'] !== __FILE__) {
return false;
}
require __DIR__ . '/../vendor/autoload.php';
require '../app/middleware/ipfilter.php';
// Instantiate the app
$settings = require __DIR__ . '/../app/settings.php';
$app = new \Slim\App($settings);
$app->get('/test', function() {
echo "You look like you're from around here";
});
// Set up dependencies
require __DIR__ . '/../app/dependencies.php';
// Register middleware
require __DIR__ . '/../app/middleware.php';
// Register routes
require __DIR__ . '/../app/routes.php';
$app->add(new IpFilter);
// Run
$app->run();
我正在为我的项目设置使用slim skeleton project。运行此代码时出现以下错误。
Fatal error: Class 'IpFilter' not found in
/Applications/XAMPP/xamppfiles/htdocs/slimtest/my-app/public/index.php
on line 34
我仍然不明白如何在 slim 中为中间件添加自定义类。我看过几个教程,它们只是制作课程并使用$app->add('new class) 添加中间件,但我无法弄清楚。是否有我需要更新的文件而我只是错过了它?
这是一个漫长的周末,资源不多,因此我们将不胜感激。
更新:
当我从 ipfilter.php 中删除 namespace App\Middleware 时,我没有得到同样的错误。这次我明白了
Fatal error: Call to undefined method IpFilter::request() in /Applications/XAMPP/xamppfiles/htdocs/slimtest/my-app/app/middleware/ipfilter.php on line 15
我明白为什么,但我认为这可能有助于解决问题并找到问题的根源。
【问题讨论】:
-
你搞清楚了吗?
-
@rob 我做到了。花了几个小时但很简单的修复。
标签: php middleware slim-3