我不明白Laravel听和开火的区别。
基本上,我知道他们的概念,但实际上我搞不懂。
当用户访问pages/show时,我想回显一个文本。这是我的控制器:
class Pages extedns Controller
{
function show ()
{
echo "Welcome to our website.";
}
}
现在这是我的代码块事件追加到global.php:
Event::listen("Pages.show", function(){
echo "You have listened to one event!";
});
现在,上述事件应该如何触发?我应该如何期望它工作?因为这种方法行不通。但是,当我将以下行添加到这段代码中时,它就工作了:
Event::fire("Pages.show");
现在,问题是事件在我访问的每个页面和控制器中都被触发了。它不考虑Pages。Show controller-method,它只是触发它。如果有专家帮我解惑,我将不胜感激
事件侦听器仅由字符串标识,它们与应用程序的任何其他部分无关,为了简单地说明这一点,您可以使用以下内容
Event::listen("logged",function($user){
logEvent("{$user} logged in."); // Supposing that logEvent would write the message to a file.
});
当用户进行身份验证时,也就是密码和用户名存在且匹配时,就会触发事件,它看起来像这样
if($user->attemptLogin("myuser","password")){ //If the authentication function returns true
Event::fire("logged",array($user->name)); //Fire the event and pass the username to be logged.
}
对所有Laravel开发人员的注意:我知道有一个身份验证方法,但我试图在这里保持简单。
基本上你在做的是你给一段代码一个字符串标识符,你可以通过触发它的事件在代码上调用那块。
现在,离开我的例子,你试图听一个函数,正如我说的事件标识符只是字符串,不链接到任何其他东西,所以解决方案是简单地调用事件火在你的函数: 侦听器:Event::listen("showedPage", function(){
echo "You have listened to one event!";
});
触发:
class Pages extends Controller
{
function show ()
{
echo "Welcome to our website.";
Event::fire("showedPage");
}
}
因此,每次调用show函数时,您将"触发"或"触发"侦听器中的代码块。
请注意,我更改了事件的名称,以表示它与被调用的函数没有直接关系。