我想将中间件添加到我的 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();
我正在为我的项目设置使用一个纤薄的骨架项目。运行此代码时出现以下错误。
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)
添加中间件,但我无法弄清楚。是否有我需要更新的文件而我只是错过了它?
这是一个漫长的周末,那里的资源不多,所以任何帮助都将不胜感激。
更新:
当我namespace App\Middleware
从 ipfilter.php 中删除时,我没有得到同样的错误。这次我得到
Fatal error: Call to undefined method IpFilter::request() in /Applications/XAMPP/xamppfiles/htdocs/slimtest/my-app/app/middleware/ipfilter.php on line 15
我明白为什么,但我认为它可能有助于排除故障并找到问题的根源。