Skip to content

Instantly share code, notes, and snippets.

@Big-Shark
Last active August 29, 2015 14:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Big-Shark/6281b36af7765c0cb89f to your computer and use it in GitHub Desktop.
Save Big-Shark/6281b36af7765c0cb89f to your computer and use it in GitHub Desktop.
Как подключать пропел 2, в ларавель5

Все достаточно легко, первое это добавить пропел в проект через композер, все это описано на сайте пропела и не вызывает проблем.

Дальше несколько путей, если есть БД и если нет, я опишу сейчас путь при котором мы будем использовать стандартную авторизацию ларавель 5, а соответственно нам понадобятся его таблицы.

1 Установить пропел, я думаю вы это уже сделали

2 Дальше чтобы не лазить постоянно в папку вендоров к бин файлу, я вынес его в корень проекта, команда

ln -s vendor/bin/propel propel

3 на этом этапе мы должны создать схему, но так как мы будем использовать авторизацию от лары, нам пока еще рано это делать )

4 Чтобы создать базу, нужно применить ларавль миграции стандартным для них способом.

5 Удаляем миграции и удаляем таблицу миграций из БД

6 создаем конфиг, я создал propel.php в папке конфигов с таким содержание

<?php

if( ! function_exists('app') or app() == null)
{
    require __DIR__.'/../bootstrap/autoload.php';
    $app = require_once __DIR__.'/../bootstrap/app.php';
    \Container\Container::setInstance($app);
    (new Illuminate\Foundation\Bootstrap\DetectEnvironment())->bootstrap($app);
}

return [
    'propel' => [
        'database' => [
            'connections' => [
                'default' => [
                    'adapter'    => 'mysql',
                    'classname'  => 'Propel\Runtime\Connection\ConnectionWrapper',
                    'dsn'        => 'mysql:host='.env('DB_HOST', 'localhost').';dbname='.env('DB_DATABASE', 'forge'),
                    'user'       => env('DB_USERNAME', 'forge'),
                    'password'   => env('DB_PASSWORD', ''),
                    'attributes' => [],
                    'settings'   => [
                        'charset'=> 'utf8',
                        'queries' => [
                            'utf8' => "SET NAMES utf8 COLLATE utf8_unicode_ci, COLLATION_CONNECTION = utf8_unicode_ci, COLLATION_DATABASE = utf8_unicode_ci, COLLATION_SERVER = utf8_unicode_ci"
                        ]
                    ]
                ]
            ]
        ],
        'runtime' => [
            'defaultConnection' => 'default',
            'connections' => ['default']
        ],
        'generator' => [
            'defaultConnection' => 'default',
            'connections' => ['default'],
            'namespaceAutoPackage' => false
        ],
        ### Directories and Filenames ###
        'paths' => [
              # Directory where the project files (`schema.xml`, etc.) are located.
              # Default value is current path #
              'projectDir'=>  base_path(),

              # The directory where Propel expects to find your `schema.xml` file.
              'schemaDir' => base_path(),

              # The directory where Propel should output classes, sql, config, etc.
              # Default value is current path #
              'outputDir' => app_path(),

              # The directory where Propel should output generated object model classes.
              'phpDir' => app_path(),

              # The directory where Propel should output the compiled runtime configuration.
              'phpConfDir' => base_path().'/config/propel',

              # The directory where Propel should output the generated migrations.
              'migrationDir' => base_path().'/database/migrations',

              # The directory where Propel should output the generated DDL (or data insert statements, etc.)
              'sqlDir' => base_path().'/database',

              # Directory in which your composer.json resides
              'composerDir'=> base_path(),
        ]
    ]
];

7 Выгружаем старую базу в файл схему

propel reverse default

8 Проверяем схему, я поменяю phpName с Users на User и PasswordResets на PasswordReset

9 Удаляем старый файл юзер из папки апп

10 Заполняем базу

propel migration:diff
propel migration:up

11 билдим модельки

propel model:build

12 Генерим рантайм конфиг

propel config:convert

13 В файл bootstrap/autoload.php после строки require DIR.'/../vendor/autoload.php'; пишем

require __DIR__ .'/../config/propel/config.php';

14 Меняем создание пользователя в файле app/Services/Registrar.php

	public function create(array $data)
	{
		$user = new User();
		$user->setName($data['name']);
		$user->setEmail($data['email']);
		$user->setPassword(bcrypt($data['password']));
		$user->save();
		return $user;
	}

15 Создаем app/Services/AuthManager.php

<?php namespace App\Services;

use Illuminate\Auth\AuthManager as IlluminateAuthManager;
use App\UserQuery as UserQuery;
use App\Providers\PropelUserProvider as PropelUserProvider;
use Illuminate\Auth\Guard;

class AuthManager extends IlluminateAuthManager {

    /**
     * Create an instance of the propel driver.
     *
     * @return \Illuminate\Auth\Guard
     */
    public function createPropelDriver()
    {
        $provider = new PropelUserProvider(UserQuery::create(), $this->app['hash']);

        return new Guard($provider, $this->app['session.store']);
    }

}

16 Создаем app/Providers/PropelUserProvider.php

<?php namespace App\Providers;

use App\UserQuery;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Auth\UserProviderInterface as UserProviderInterface;

class PropelUserProvider implements UserProviderInterface {

    /**
     * The active propel query.
     *
     * @var \App\UserQuery
     */
    protected $query;

    /**
     * The hasher implementation.
     *
     * @var \Illuminate\Contracts\Hashing\Hasher
     */
    protected $hasher;

    /**
     * Create a new database user provider.
     *
     * @param  \App\UserQuery  $query
     * @param  \Illuminate\Contracts\Hashing\Hasher  $hasher
     * @return void
     */
    public function __construct(UserQuery $query, HasherContract $hasher)
    {
        $this->query = $query;
        $this->hasher = $hasher;
    }

    /**
     * Retrieve a user by their unique identifier.
     *
     * @param  mixed  $identifier
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveById($identifier)
    {
        return $this->query->findPK($identifier);
    }

    /**
     * Retrieve a user by by their unique identifier and "remember me" token.
     *
     * @param  mixed   $identifier
     * @param  string  $token
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByToken($identifier, $token)
    {
        return $this->query->filterById($identifier)
            ->filterByRememberToken($token)
            ->findOne();
    }

    /**
     * Update the "remember me" token for the given user in storage.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  string  $token
     * @return void
     */
    public function updateRememberToken(UserContract $user, $token)
    {
        $this->query->filterById($user->getAuthIdentifier())
            ->update(['remember_token' => $token]);
    }

    /**
     * Retrieve a user by the given credentials.
     *
     * @param  array  $credentials
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials)
    {
        $query = $this->query;
        foreach ($credentials as $key => $value)
        {
            if ( ! str_contains($key, 'password'))
            {
                $query->where('User.'.$key . ' = ?', $value);
            }
        }

        return $query->findOne();
    }


    /**
     * Validate a user against the given credentials.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  array  $credentials
     * @return bool
     */
    public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials['password'];

        return $this->hasher->check($plain, $user->getAuthPassword());
    }

}

17 Изменяем файл пользователя следуюшим образом

<?php

namespace App;

use App\Base\User as BaseUser;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

/**
 * Skeleton subclass for representing a row from the 'users' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 */
class User extends BaseUser implements AuthenticatableContract, CanResetPasswordContract
{
    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
        return $this->getId();
    }

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->getPassword();
    }

    public function getRememberTokenName()
    {
        throw Exception('This is deprecated function');
    }

    /**
     * Get the e-mail address where password reset links are sent.
     *
     * @return string
     */
    public function getEmailForPasswordReset()
    {
        return $this->getEmail();
    }
}

Вот и все, но я надеюсь вы не пошли моим путем, а поставили пропер драйвер для ларавеля и избежали всего этого ))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment