2013-09-15 4 views
0

Я использую класс User, включенный в laravel 4. Я пытаюсь сохранить новый вопрос, который принадлежит пользователю, и пользователь должен войти в систему для создания. когда я звоню в магазин действий вопросы контроллера я получаю следующую ошибкуlaravel abstract method fatal error error

Class User contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (Illuminate\Auth\UserInterface::getAuthPassword, Illuminate\Auth\Reminders\RemindableInterface::getReminderEmail) 

Я прочитал немного на абстрактных методов в PHP, и пока я не совсем понимаю их ошибка сама дает два решения этой проблемы, объявить аннотация класса для реализации методов репарации. Я предполагаю, что, поскольку это модельный класс, который поставляется с laravel, правильным решением является не изменение его объявления на абстрактное, а реализация остальных методов. Как сделать это правильно в этом случае и идти вперед?

пользователя Модель

<?php 

use Illuminate\Auth\UserInterface; 
use Illuminate\Auth\Reminders\RemindableInterface; 

class User extends BaseModel implements UserInterface, RemindableInterface { 

    protected $guarded = []; 

    public static $rules = array(
     'username' => 'required|unique:users|alpha_dash|min:4', 
     'password' => 'required|alpha_num|between:4,8|confirmed', 
     'password_confirmation'=>'required|alpha_num|between:4,8' 
     ); 

    public function Questions($value='') 
    { 
     return $this->hasMany('Question'); 

    } 

    /** 
    * The database table used by the model. 
    * 
    * @var string 
    */ 
    protected $table = 'users'; 

    /** 
    * The attributes excluded from the model's JSON form. 
    * 
    * @var array 
    */ 
    protected $hidden = array('password'); 

    /** 
    * Get the unique identifier for the user. 
    * 
    * @return mixed 
    */ 
    public function getAuthIdentifier() 
    { 
     return $this->getKey(); 
    } 

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

    /** 
    * Get the e-mail address where password reminders are sent. 
    * 
    * @return string 
    */ 
    public function getReminderEmail() 
    { 
     return $this->email; 
    } 

} 

Вопросы контроллер

/** 
    * Store a newly created resource in storage. 
    * 
    * @return Response 
    */ 
    public function postStore() 
    { 
     $validation = Question::validate(Input::all()); 

     if($validation->passes()) { 
      Question::create(array(
       'question'=>Input::get('question'), 
       'user_id'=>Auth::user()->id 
      )); 

      return Redirect::Route('home') 
      ->with('message', 'Your question has been posted.'); 

     } else { 
      return Redirect::to('user/register')->withErrors($validation) 
      ->withInput(); 
     } 
    } 

редактировать 1: Сообщение об ошибке включает в себя «(ILLUMINATE \ Auth \ :: getAuthPassword пользовательского интерфейса, подсветите \ Auth \ Памятку \ RemindableInterface :: getReminderEmail) «эти два метода находятся в моем user.php как функции публикации, как вы можете видеть выше, поэтому мне нужно сделать что-то еще, чтобы« реализовать »их?

редактировать 2:

Laravel Src класса пользовательским интерфейсом

<?php namespace Illuminate\Auth; 

interface UserInterface { 

    /** 
    * Get the unique identifier for the user. 
    * 
    * @return mixed 
    */ 
    public function getAuthIdentifier(); 

    /** 
    * Get the password for the user. 
    * 
    * @return string 
    */ 
    public function getAuthPassword(); 

} 

Laravel ЦСИ RemindableInterface класс

<?php namespace Illuminate\Auth\Reminders; 

interface RemindableInterface { 

    /** 
    * Get the e-mail address where password reminders are sent. 
    * 
    * @return string 
    */ 
    public function getReminderEmail(); 

} 

редактировать 3:

php.ini связанные ошибки отчетности

; error_reporting 
; Default Value: E_ALL & ~E_NOTICE 
; Development Value: E_ALL | E_STRICT 
; Production Value: E_ALL & ~E_DEPRECATED 

error_reporting = E_ALL 

; Eval the expression with current error_reporting(). Set to true if you want 
; error_reporting(0) around the eval(). 
; http://php.net/assert.quiet-eval 
;assert.quiet_eval = 0 

basemodel класс

<?php 

class Basemodel extends Eloquent { 

    public static function validate($data) { 

     return Validator::make($data, static::$rules); 
    } 
} 


?> 

редактировать 4;

Добавление правильный класс модели, как это было, когда дает ошибку и как теперь с исправлением

<?php 

use Illuminate\Auth\UserInterface; 
use Illuminate\Auth\Reminders\RemindableInterface; 

class Question extends BaseModel implements UserInterface, RemindableInterface { 

    protected $guarded = []; 

    public static $rules = array(
      'questions'=>'required|min:10|max:255', 
      //'solved'=>'in:0,1', 
     ); 

    /** 
    * The database table used by the model. 
    * 
    * @var string 
    */ 
    protected $table = 'questions'; 

    /** 
    * The attributes excluded from the model's JSON form. 
    * 
    * @var array 
    */ 
    protected $hidden = array(''); 

    /** 
    * Get the unique identifier for the question. 
    * 
    * @return mixed 
    */ 
    public function getAuthIdentifier() 
    { 
     return $this->getKey(); 
    } 

    public function user() 
    { 
     return $this->belongsTo('User'); 
    } 

} 

добавить это исправить

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

    /** 
    * Get the e-mail address where password reminders are sent. 
    * 
    * @return string 
    */ 
    public function getReminderEmail() 
    { 
     return $this->email; 
    } 

ответ

2

Может быть, это проще всего ответить на этот вопрос на примере , Скажем, у меня есть следующие классы:

abstract class ClassB { 
    public abstract function foo(); 
} 

class ClassA extends ClassB {} 

$a = new ClassA(); 

Выполнение этого кода приведет к следующей ошибке:

Fatal error: Class ClassA contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (ClassB::foo) 

Это означает, что я пропускаю реализацию foo() (определенный в ClassB) в ClassA. Абстрактные методы могут быть определены только в абстрактных классах и означают, что любой неабстрактный производный класс должен раскрывать полную реализацию, которая в этом случае не является ClassA.Приведенный выше пример может быть исправлена ​​путем изменения ClassA к

class ClassA extends ClassB { 

    // implementation of abstract ClassB::foo(). 
    public function foo() { 
     echo 'Hello!'; 
    } 
} 

Назад к вашему примеру. Ваш класс User распространяется BaseModel. В зависимости от того, BaseModel расширяет еще один абстрактный класс, он будет содержать два метода, определяемых как abstract, что отсутствует класс User. Вам нужно найти эти методы - мое сообщение об ошибке явно сообщило мне, что мне не хватает, и реализовать их в User.

+0

Спасибо за ответ, см. Мое редактирование – Ir1sh

+0

Можете ли вы добавить полные подписи этих двух методов к своему вопросу? Вы должны убедиться, что подписи ваших реализаций совпадают (с равной или большей видимостью). –

+0

Я не совсем уверен, что вы подразумеваете под полными подписями, извините, но я сделал предположение, посмотрю на редактирование 2 – Ir1sh