我对Silex PHP中的开发有两个疑问。
usersController.php
namespace myworkplaces\controllers;
use Silex\Application;
use Silex\Api\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use myworkplaces\models;
class usersController implements ControllerProviderInterface {
public function connect(Application $app) {
$controllers = $app['controllers_factory'];
$controllers->put('/login', array($this, 'login'))->bind('login');
return $controllers;
}
public function login(Application $app, Request $request) {
$email = $app->escape($request->get('email'));
$password = $app->escape($request->get('password'));
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
return $app->json(array ('type' => 'error', 'message' => 'El email no tiene el formato correcto.'), 202);
if (strlen($password) < 5)
return $app->json(array ('type' => 'error', 'message' => 'La contraseña no puede ser menor a 6 carácteres.'), 202);
if (models\usersModel::checkLogin($app, $email, $password)) {
return $app->json(array ('type' => 'info', 'message' => '¡Ten un buen día!'), 201);
} else {
return $app->json(array ('type' => 'error', 'message' => 'Error en la autentificación.'), 202);
}
}}
usersModel.php
namespace myworkplaces\models;
class usersModel {
function checkEmail($app, $email) {
if (($app['db']->users)->findOne([ 'email' => $email ], [ 'projection' => [ 'email' => 1 ] ]) != NULL) {
return true;
} else {
return false;
}
}
function getDataUser($app, $id) {
return ($app['db']->users)->findOne([ '_id' => new \MongoDB\BSON\ObjectID($id) ]);
}
function checkLogin($app, $email, $password) {
if (!checkEmail($app, $email))
return false;
if (password_verify($password, ($app['db']->users)->findOne([ 'email' => $email ], [ 'projection' => [ 'hashPassword' => 1 ] ])['hashPassword'])) {
$user = getDataUser($app, (string)getID($email));
$app['session']->set('user', array('id' => (string)$user['_id'], 'email' => $user['email'], 'username' => $user['username'], 'superadmin' => $user['superadmin'], 'adminPlaces' => $user['adminPlaces']));
return true;
} else {
return false;
}
}}
要访问myworkplaces \ models命名空间内和usersModel类中的checkLogin()函数,我只能使用此调用models \ usersModel :: checkLogin()进行访问,我不认为它是正确的事情。我不应该能够使用models \ usersModel \ checkLogin()?
调用该函数第二个问题是在函数checkLogin中,我想在同一个命名空间内和同一个类中调用checkEmail函数,但是通过像checkEmail()这样的调用你应该能够无错误地调用它。发生的错误是,尝试调用函数&#34; checkEmail&#34;来自命名空间&#34; myworkplaces \ models&#34;。问题在哪里?
我使用作曲家的自动加载
"autoload": {
"psr-4": {
"myworkplaces\\": "src/"
}
}
谢谢!
答案 0 :(得分:0)
这里我假设没有其他语法错误,你的类加载器工作正常。
在controller.php
将其更改为:
if (models\usersModel::checkLogin($app, $email, $password)) {
:此:强>
if (\myworkplaces\models\usersModel::checkLogin($app, $email, $password)) {
在usersModel.php
将其更改为:
function checkEmail($app, $email) {
:此:强>
public function static checkEmail($app, $email) {
将其更改为:
if (!checkEmail($app, $email))
:此:强>
if (!self::checkEmail($app, $email))