cakephp 3-设置语言并将其存储在cookie中

时间:2018-09-04 07:41:13

标签: cakephp cookies

首先,我想说声你好,这是我在这里问的第一个问题:)。

我在理解cakephp3.x中的cookie时遇到了问题。我从here制作了书签教程。后来,我添加了国际化功能,可以在其中选择英语和波兰语。 (准确地说)有两个我不知道的问题。

如果您中的任何人-完成了该教程,我只能在Users链接上获取我的国际化版本。我检查了UsersController几次。

第二件事:在我的应用中,当我选择两种语言中的一种并选择另一种操作时(例如:新标签->列出书签),语言仍然相同-很好,但是我不知道为什么。我不应该使用Cookies还是将其存储在会话中?

在那些文件中它可能被弄乱了:

UsersComponent.php

<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\Event\Event;
use Cake\Controller\Controller;
use Cake\Core\Configure;
use Cake\I18n\I18n;
use Cake\Core\Configure\Engine\PhpConfig;


/**
 * Users Controller
 *
 * @property \App\Model\Table\UsersTable $Users
 *
 * @method \App\Model\Entity\User[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
 */

class UsersController extends AppController
{

    public function beforeFilter(Event $event)
    {

        if ($this->Auth->user())
        {
            //$this->viewBuilder()->setLayout('logged-in');
            echo Configure::read('User.nick');
        }

        $myLang = $this->getRequest()->getSession()->read('Config.language');
        Configure::write('Config', [
            'language' => $myLang,
        ]);
        I18n::setLocale($myLang);

    }

    public function login()
    {
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            if ($user) {
                $this->Auth->setUser($user);

                $this->getRequest()->getSession()->write('Config.language', 'pl');

                return $this->redirect('/');
            }
            $this->Flash->error('Your username or password is incorrect.');
        }
        $this->viewBuilder()->setLayout('default');


    }

    /**
     * Index method
     *
     * @return \Cake\Http\Response|void
     */
    public function index()
    {
        $users = $this->paginate($this->Users);

        $this->set(compact('users'));
    }

    /**
     * View method
     *
     * @param string|null $id User id.
     * @return \Cake\Http\Response|void
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => ['Bookmarks']
        ]);

        $this->set('user', $user);

    }

    /**
     * Add method
     *
     * @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $user = $this->Users->newEntity();
        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
        $this->set(compact('user'));
        //$this->log($user);
        //$this->viewBuilder()->setLayout('logged-in');
        //echo Configure::read('User.nick');
    }

    /**
     * Edit method
     *
     * @param string|null $id User id.
     * @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
        $this->set(compact('user'));
    }

    /**
     * Delete method
     *
     * @param string|null $id User id.
     * @return \Cake\Http\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $user = $this->Users->get($id);
        if ($this->Users->delete($user)) {
            $this->Flash->success(__('The user has been deleted.'));
        } else {
            $this->Flash->error(__('The user could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }

    public function initialize()
    {
        parent::initialize();
        // Add the 'add' action to the allowed actions list.
        $this->Auth->allow(['logout', 'add']);

    }

    public function logout()
    {
        $this->Flash->success('You are now logged out.');
        return $this->redirect($this->Auth->logout());

    }

    /**/
        public function register()
        //Moja funkcja register - Start
        {
            $user = $this->Users->newEntity();
            $this->log($user);
            if ($this->request->is('post')) {
                $this->Users->patchEntity($user,$this->request->getData());

                $this->log($user);

                //$this->log($this->request->getData());
                if($this->Users->save($user))
                {
                    $this->Flash->success('You are registered and now can login');
                    return $this->redirect(['action' => 'login']);
                }
                else
                {
                    $this->Flash->error('An error has occured, you need to repeat registration');
                    return $this->redirect(['action' => 'register']);
                }
                if ($user)
                {
                    //$this->Auth->setUser($user);

                    //$this->getRequest()->getSession()->read('Config.language');

                    //return $this->redirect('/');
                }
            }
            //$this->log($user);
            //$this->set('user', $user);
            //$this->set('_serialize', ['user']);
            $this->set(compact('user'));
            $this->viewBuilder()->setLayout('register');

            //return true;
        }
        //Moja funkcja register - Koniec


    /*public function register()
    {
        $user = $this->Users->newEntity($this->request->getData());
        if ($this->Users->save($user)) {
            $this->Auth->setUser($user->toArray());

        }

        return $this->redirect(['action' => 'register']);

    }


    /*
        public function register()
        //funkcja skądś z internetu - Start
        {
            $user = $this->Users->newEntity();
            if($this->request->is('post')) {
                $this->Users->patchEntity($user,$this->request->data);
                if($this->Users->save($user)){
                    $this->Flash->success(__('Your account has been registered .'));
                    return $this->redirect(['action' => 'index']);
                }
                $this->Flash->error(__('Unable to register your account.'));
            }
            $this->set('user',$user);
            $this->viewBuilder()->setLayout('register');
        }
        //funkcja skądś z internetu - Koniec
    */

    public function isAuthorized($user)
    {
        $action = $this->request->getParam('action');

        if (in_array($action, ['index', 'add', 'tags', 'delete', 'view', 'edit', 'international', 'change'])) {
            $this->viewBuilder()->setLayout('logged-in');
            return true;
                }


        if (!$this->request->getParam('pass.0')) {
            return false;
        }

        return parent::isAuthorized($user);
    }
}

AppController.php

<?php
/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @link      https://cakephp.org CakePHP(tm) Project
 * @since     0.2.9
 * @license   https://opensource.org/licenses/mit-license.php MIT License
 */
namespace App\Controller;

use Cake\Event\Event;
use Cake\Controller\Controller;
use Cake\Core\Configure;
use Cake\Core\Configure\Engine\PhpConfig;
use Cake\I18n\I18n;

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @link https://book.cakephp.org/3.0/en/controllers.html#the-app-controller
 */


class AppController extends Controller
{

    public function beforeFilter(Event $event)
    {
        if($myUser = $this->Auth->user()){

            Configure::write('User', [
                'nick' => $myUser['nick'],
            ]);
        }


        $myLang = $this->getRequest()->getSession()->read('Config.language');
        Configure::write('Config', [
            'language' => $myLang,
        ]);
        I18n::setLocale($myLang);
    }


    public function beforeRender(Event $event)
    {

            //echo I18n::getLocale();

    }

    public function initialize()
    {
        $this->loadComponent('Flash');
        $this->loadComponent('Auth', [
            'authorize' => 'Controller',
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'nick' => 'nick',
                        'username' => 'email',
                        'password' => 'password'
                    ]
                ]

            ],
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'

            ],
            'unauthorizedRedirect' => $this->referer() // If unauthorized, return them to page they were just on
        ]);
        // Allow the display action so our pages controller
        // continues to work.
        $this->Auth->allow(['display','register','add']);

    }

    public function isAuthorized($user)
    {
        return true;
    }
}

InternationlizationsController.php

<?php

namespace App\Controller;
use App\Controller\AppController;
use Cake\I18n\I18n;
use Cake\Core\Configure;

class InternationalizationsController extends AppController{

    public function change($lang = NULL){

        $this->getRequest()->getSession()->write('Config.language', $lang);
        $this->redirect($this->referer());
    }

    public function isAuthorized($user)
    {
        $action = $this->request->getParam('action');

        if (in_array($action, ['index', 'add', 'tags', 'delete', 'view', 'edit', 'international', 'change','register'])) {
            $this->viewBuilder()->setLayout('logged-in');
            return true;
        }


        if (!$this->request->getParam('pass.0')) {
            return false;
        }

        return parent::isAuthorized($user);
    }
}
?>

Folder structure screenshot

0 个答案:

没有答案