【问题标题】:PHP - Where to implement Session Logic in MVC?PHP - 在哪里实现 MVC 中的会话逻辑?
【发布时间】:2015-06-30 13:29:54
【问题描述】:

访问我的应用程序(按顺序)

  1. 白名单ip地址
    • 在无效 ip 上重定向到 404
  2. 检查上次活动是否是 > 2 小时前
    • 重定向到登录页面并过期会话
  3. 通过查看 $_SESSION 中的用户数据来检查用户是否已登录
    • 如果无效则重定向到登录页面

索引.php

(注意它与this问题非常相似):

/**
 * Set Timezone
 */
date_default_timezone_set('Zulu');

/**
 * Include globals and config files
 */
require_once('env.php');

/*
 * Closure for providing lazy initialization of DB connection
 */
$db = new Database();

/* 
 * Creates basic structures, which will be 
 * used for interaction with model layer.
 */
$serviceFactory = new ServiceFactory(new RepositoryFactory($db), new EntityFactory);
$serviceFactory->setDefaultNamespace('\\MyApp\\Service');

$request = new Request();
$session = new Session();
$session->start();
$router = new Router($request, $session);

/*
 * Whitelist IP addresses
 */
if (!$session->isValidIp()) {
    $router->import($whitelist_config);

/*
 * Check if Session is expired or invalid
 */
} elseif (!$session->isValid()) {
    $router->import($session_config);

/*
 * Check if user is logged in
 */
} elseif (!$session->loggedIn()) {
    $router->import($login_config);
} else {
    $router->import($routes_config);
}

/*
 * Find matched route, or throw 400 header.
 *
 * If matched route, add resource name 
 * and action to the request object.
 */
$router->route();

/* 
 * Initialization of View 
 */
$class = '\\MyApp\\View\\' . $request->getResourceName();
$view = new $class($serviceFactory);

/*
 * Initialization of Controller
 */
$class = '\\MyApp\\Controller\\' . $request->getResourceName();
$controller = new $class($serviceFactory, $view);

/*
 * Execute the necessary command on the controller
 */
$command = $request->getCommand();
$controller->{$command}($request);

/*
 * Produces the response
 */
echo $view->render();

$router->import() 函数获取一个带有路由配置的 json 文件并创建路由(我还没有决定是否要保留它)。我的路由器是Klein的修改版。

我的问题

这是如何检查会话数据的正确实现吗?

我更愿意检查会话中的用户数据是否可以在数据库中找到,但我需要为此使用服务,并且服务只能由控制器访问(?)。我不知道将用户发送到哪个控制器,因为如果用户登录,路由配置会改变。

例如,如果有人试图访问 www.myapp.com/orders/123,如果他们已登录,我会将其发送到 Orders 控制器,如果他们已登录,我会将其发送到 Session 控制器(以呈现登录页面)不是。

我已阅读this 问题中的 ACL 实现。但是,除非我弄错了,那是为了控制已经登录的用户的访问,而不是控制未登录的用户的访问。如果不是这样,有人可以解释一下我将如何实施我的 ACL 来检查这个?

我非常感谢任何帮助,因为搜索此答案给了我非常复杂的解决方案,其中大多数我不喜欢或看起来不像干净的解决方案。就像一个会话管理器,这基本上是我正在做的,但假装没有。 =/

更新 index.php(我的解决方案)

/**
 * Set Timezone
 */
date_default_timezone_set('Zulu');

/**
 * Include globals and config files
 */
require_once('env.php');

/*
 * Closure for providing lazy initialization of DB connection
 */
$db = new Database();

/* 
 * Creates basic structures, which will be 
 * used for interaction with model layer.
 */
$serviceFactory = new ServiceFactory(new MapperFactory($db), new DomainFactory);
$serviceFactory->setDefaultNamespace('\\MyApp\\Service');

include CONFIG_PATH.'routes.php';

$request = new Request();
$router = new Router($routes,$request);

/*
 * Find matched route.
 *
 * If matched route, add resource name 
 * and command to the request object.
 */
$router->route();

$session = $serviceFactory->create('Session');

/*
 * Whitelist Ip address, check if user is 
 * logged in and session hasn't expired.
 */
$session->authenticate();

/*
 * Access Control List
 */
include CONFIG_PATH.'acl_settings.php';

$aclFactory = new AclFactory($roles,$resources,$rules);
$acl = $aclFactory->build();

$user = $session->currentUser();
$role = $user->role();
$resource = $request->getResourceName();
$command = $request->getCommand();

// User trying to access unauthorized page
if (!$acl->isAllowed($role, $resource, $command) {
    $request->setResourceName('Session');
    $request->setCommand('index');
    if ($role === 'blocked') {
        $request->setResourceName('Error');
    }
}

/* 
 * Initialization of View 
 */
$class = '\\MyApp\\View\\' . $request->getResourceName();
$view = new $class($serviceFactory, $acl);

/*
 * Initialization of Controller
 */
$class = '\\MyApp\\Controller\\' . $request->getResourceName();
$controller = new $class($serviceFactory, $view, $acl);

/*
 * Execute the necessary command on the controller
 */
$command = $request->getCommand();
$controller->{$command}($request);

/*
 * Produces the response
 */
$view->{$command}
$view->render();

我在 Session 模型中启动会话并授权用户。会话的 currentUser 如果未登录,则角色为“guest”,如果其 IP 地址不在白名单中,则为“blocked”。我想按照 teresko 以前的 ACL 帖子的建议实现控制器包装器,但我需要一些可以重定向用户的东西。如果他们尝试访问不允许访问的页面,我会将他们发送到他们的主页 (Session#index),如果他们被阻止,我会将其发送到 Error#index。 Session#index 将让 View 决定是否显示登录用户的主页,或者如果他们没有登录则显示登录页面(通过检查用户的角色)。也许不是最好的解决方案,但似乎也不算太糟糕。

【问题讨论】:

  • 我会说会话是持久性的形式。因此 - 它可能应该进入各种映射器。至于那个古老的 ACL 帖子,您可以将 $currentUser 在未经身份验证时设为匿名。并对那些匿名用户有特定的访问规则。哦..这些答案有点过时了:(
  • @tereško 请先写一本书,这样我就可以阅读了。它们可能已经过时了,但它仍然让我比大多数教程更好地理解了这些概念。无论如何,所以你是说我应该有一个映射器用于会话?或者我应该在各种映射器中实现会话?
  • @tereško 重新阅读您的评论。显然,您的意思是多个映射器,因此是“各种”一词。另外,我真的很喜欢“匿名用户”,谢谢。

标签: php session model-view-controller architecture


【解决方案1】:

单一职责

您的会话对象正在做太多事情。会话或多或少只是为了跨请求的持久性。会话不应执行任何身份验证逻辑。您将登录用户的标识符存储在会话中,但实际验证、登录/注销应在身份验证服务中完成。

路线管理

根据用户身份验证状态导入不同的路由将无法很好地扩展,并且当您有更多路由时,以后调试会很痛苦。最好将所有路由定义在一个地方,并在未经授权的情况下使用身份验证服务进行重定向。我对那个路由器不是很熟悉,但是查看文档你应该可以像

$router->respond(function ($request, $response, $service, $app) { 
    $app->register('auth', function() {
        return new AuthService();
    }
});

然后在您需要登录的路线上,您可以执行类似的操作

$router->respond('GET', '/resource', function ($request, $response, $service, $app) {
    if( ! $app->auth->authenticate() )
        return $response->redirect('/login', 401);
    // ...
});

【讨论】:

  • 那么,我需要为每个资源添加if ( ! $app->auth->authenticate() ) 和重定向吗?不是控制器的应用程序对象与服务交互是否可以?另外,我会在 app 对象中实现 ACL 吗?像$app->register('acl' function() { return new ACL(); } 之类的东西,然后……if (! $app->acl->allowedResource($resource) ) ……重定向?
  • 对于身份验证,您可以将其放入每个安全路由中,但根据应用程序其余部分的结构,将其放入路由过滤器/组或中间件可能会更容易。您为 ACL 提供的解决方案应该可以工作。在这种情况下,app 对象充当容器,除了存储它以便于访问之外,它并没有真正与服务“交互”。将服务视为您与业务逻辑的接口。您的 Http 逻辑应该只是通往您的业务逻辑的途径。 Http 逻辑包括控制器和路由器。
  • 谢谢。我想我只是感到困惑,因为我不希望我的身份验证业务逻辑泄露到我的控制器中。我将使用更改后的 index.php 更新我的答案,以供其他人查看。我采用了与我们讨论的不同的方法,但这是一个相似的概念。接受你的回答。
猜你喜欢
  • 2011-12-26
  • 1970-01-01
  • 2023-04-07
  • 2011-05-30
  • 2011-06-03
  • 2011-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多