Where should I log visited urls?

Notice: This thread is very old.
netteman
Member | 125
+
0
-

Hi,

I'd like to log visited urls in the base presenter.

Should I do this in __construct, beforeRender or startup ?

Thank you :)

srigi
Nette Blogger | 558
+
0
-

Try intercepting a request:

// bootstrap.php
// ...
$container = $configurator->createContainer();

$logHandler = $container->getByType(App\Services\LogHandler::class);
$application = $container->getByType(Nette\Application\Application::class);
$application->onRequest[] = [$logHandler, 'request'];
$application->onError[] = [$logHandler, 'error'];

return $container;
<?php

namespace App\Services;

use App\Routing\RouterFactory;
use Exception;
use Nette\Application;
use Nette\Application\Application as NApplication;
use Nette\Http;


class LogHandler
{
	/** @var Http\Request */
	private $httpRequest;


	/**
	 * @param Http\Request $httpRequest
	 */
	public function __construct(Http\Request $httpRequest)
	{
		$this->httpRequest = $httpRequest;
	}


	/**
	 * @param NApplication $application
	 * @param Application\Request $request
	 */
	public function request(NApplication $application, Application\Request $request)
	{
		$requestPresenter = explode(':', $request->getPresenterName());
		$requestModule = $requestPresenter[0];
        // ... your logging code
	}


	public function error(NApplication $application, Exception $e)
	{
		$request = $application->getRouter()->match($this->httpRequest);
		$this->request($application, $request);
	}
}

Don't forget to register log service in config.neon

Last edited by srigi (2017-03-05 20:32)

netteman
Member | 125
+
0
-

Wow, thanks for your code :) Looks like some study time for me ahead :)

Just a question – isn't this code theoretically faster than intercepting a request?

abstract class BasePresenter extends \Nette\Application\UI\Presenter
{
    public $db;
    public $httpRequest;

    public function __construct(\Nette\Database\Context $database, \Nette\Http\Request $httpRequest){
        $this->db = $database;
        $this->httpRequest = $httpRequest;

        $this->db->table("log")
                ->insert(array(
                    "url" => $this->httpRequest->getUrl(),
                ));

    }//end construct