在zf2中更改登录用户的密码

时间:2016-09-06 01:50:36

标签: zend-framework2

我是Zf2的新手。我有用户和管理员模块。当用户登录时,我在管理员中创建了个人资料,他更改了自己的个人资料和密码。 现在我正在修改密码,但我无法理解,如何编码更改密码。我的代码如下:

我的ProfileController是:

unit Unit1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.Edit, FMX.Edit.Suggest2, FMX.Layouts, FMX.ListBox,
  FMX.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
    Button2: TButton;
    Label1: TLabel;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure esItemChange(Sender: TObject);
    procedure Edit1PresentationNameChoosing(Sender: TObject; var PresenterName: string);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  sl: TStrings;

implementation


{$R *.fmx}

type
  TIntObj = class(TObject)
  private
    FId: integer;
  public
    constructor Create(Id: integer); overload;
    function Value: integer;
  end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Edit1.ItemIndex := 3; // force choice as if it was combobox behaviour
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  Edit1.ForceDropDown; // add a button inside TEdit and use it as dropdown
end;

procedure TForm1.Edit1PresentationNameChoosing(Sender: TObject; var PresenterName: string);
begin
  inherited;
  PresenterName := 'SuggestEditStyle';
end;

procedure TForm1.esItemChange(Sender: TObject);
begin
  // occurs when ItemIndex is changed
  Label1.Text := TEdit(Sender).SelectedItem.Text + LineFeed + 'idx=' + TEdit(Sender).ItemIndex.ToString + LineFeed + 'data=';
  if TEdit(Sender).SelectedItem.Data <> nil then
    Label1.Text := Label1.Text + TIntObj(TEdit(Sender).SelectedItem.Data).Value.ToString
  else
    Label1.Text := Label1.Text + 'nil';
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  sl := TStringList.Create;
  //sl.AddObject('aaa',10); // Segmentation fault 11 under Android
  sl.AddObject('aaa',TIntObj.Create(10));
  sl.AddObject('aaabb',TIntObj.Create(20));
  sl.AddObject('aaabbbcc',TIntObj.Create(30));
  sl.AddObject('aaacc',TIntObj.Create(40));
  sl.AddObject('aaafff',TIntObj.Create(50));
  sl.AddObject('aaaggg',TIntObj.Create(60));
  Edit1.AssignItems(sl);
  Edit1.OnItemChange := esItemChange;
end;

{ TIntObject }

constructor TIntObj.Create(Id: integer);
begin
  inherited Create;
  FId := Id;
end;

function TIntObj.Value: integer;
begin
  Result := FId;
end;

end.

ProfileForm.php:

 <?php

namespace Admin\Controller;

 use Zend\Mvc\Controller\AbstractActionController;
 use Zend\View\Model\ViewModel;

 use Admin\Model\Profile;           
 use Admin\Form\ProfileForm;

 class ProfileController extends AbstractActionController
 {


protected $profileTable;  


public function getAuthService()
{
    $this->authservice = $this->getServiceLocator()->get('AuthService');  
    return $this->authservice;  
}


public function indexAction()
{
    $this->layout("layout/layout_admin");   
    /* this is used to show user email of logined user. */  
    $user_email = $this->getAuthService()->getStorage()->read(); 

    // below condition is new and for back browser validation 
    if (!$this->getServiceLocator()
            ->get('AuthService')->hasIdentity()) {
        return $this->plugin(redirect)->toRoute('login', array('action' => 'index'));
    } 

    return new ViewModel(array(
        'admin_profile' => $this->getProfileTable()->fetchAll($user_email),             
    ));


}

public function editAction()
{
    $this->layout("layout/layout_admin");  

    $id = (int) $this->params()->fromRoute('id', 0);
    if (!$id) {
        return $this->redirect()->toRoute('login', array(
            'action' => 'index'
        ));
    }

    // Get the Profile with the specified id.  An exception is thrown
    // if it cannot be found, in which case go to the index page.
    try {
        $profile = $this->getProfileTable()->getProfile($id);
    }
    catch (\Exception $ex) {
        return $this->redirect()->toRoute('profile', array(
            'action' => 'index'
        ));
    }

    $form  = new ProfileForm();
    $form->bind($profile);
    $form->get('submit')->setAttribute('value', 'Edit');

    $request = $this->getRequest();
    if ($request->isPost()) {
        $form->setInputFilter($profile->getInputFilter());
        $form->setData($request->getPost());

        if ($form->isValid()) {
            $this->getProfileTable()->saveProfile($profile);

            // Redirect to profile
            return $this->redirect()->toRoute('profile');
        }
    }

    return array(
        'id' => $id,
        'form' => $form,
    );

}

 public function changepasswordAction()
{
    $this->layout("layout/layout_admin");  

    $id = (int) $this->params()->fromRoute('id', 0);
    if (!$id) {
        return $this->redirect()->toRoute('login', array(
            'action' => 'index'
        ));
    }

    // Get the Profile with the specified id.  An exception is thrown
    // if it cannot be found, in which case go to the index page.
    try {
        $profile = $this->getProfileTable()->getProfile($id);
    }
    catch (\Exception $ex) {
        return $this->redirect()->toRoute('profile', array(
            'action' => 'index'
        ));
    }


    $form  = new ProfileForm();
    $form->bind($profile);
    $form->get('submit')->setAttribute('value', 'Change');



    $request = $this->getRequest();  


    if ($request->isPost()) {
        $form->setInputFilter($profile->getInputFilter());
        $form->setData($request->getPost()); 

        if ($form->isValid()) { 
            echo "form is valid now save the data";
        }else echo "form is invalid, don't save data";
    }


    return array(
        'id' => $id,
        'form' => $form,
    );

}


public function getProfileTable()
{
    if (!$this->profileTable) {
        $sm = $this->getServiceLocator();
        $this->profileTable = $sm->get('Admin\Model\ProfileTable');
    }
    return $this->profileTable;
}



}

型号/ Profile.php:

<?php

namespace Admin\Form;

 use Zend\Form\Form;

 class ProfileForm extends Form
 {
     public function __construct($name = null)
     {

     parent::__construct('profile');

     $this->add(array(
         'name' => 'id',
         'type' => 'Hidden',
     ));
     $this->add(array(
         'name' => 'name',
         'attributes' => array(
            'type'  => 'text',
            'required' => 'required', 
          ),
         'options' => array(
             'label' => 'Name',
         ),
     )); 
     $this->add(array(
         'name' => 'email', 
         'attributes' => array(
            'type'  => 'text',
            'required' => 'required', 
            ),
         'options' => array(
             'label' => 'Email',
         ),
     ));  


     $this->add(array(
         'name' => 'old_password',
         'attributes' => array(
            'type'  => 'password',
            'required' => 'required',
            ), 
         'options' => array(
             'label' => 'Old Password ',
         ),
     )); 
     $this->add(array(
         'name' => 'new_password', 
         'attributes' => array(
            'type'  => 'password',
            'required' => 'required', 
            ),
         'options' => array(
             'label' => 'New Password ',
         ),
     ));
     $this->add(array(
         'name' => 'confirm_password', 
         'attributes' => array(
            'type'  => 'password',
            'required' => 'required', 
            ),
         'options' => array(
             'label' => 'Confirm Password ',
         ),
     ));


     $this->add(array(
         'name' => 'submit',
         'type' => 'Submit',
         'attributes' => array(
             'value' => 'Go',
             'id' => 'submitbutton',
         ),
     ));
 }


}

型号/ ProfileTable.php:

<?php


 namespace Admin\Model;

 use Zend\InputFilter\InputFilter;
 use Zend\InputFilter\InputFilterAwareInterface;
 use Zend\InputFilter\InputFilterInterface;

 class Profile implements InputFilterAwareInterface
 {
 public $id;
 public $name;
 public $email;
 public $password;

 protected $inputFilter;

 public function exchangeArray($data)
 {
     $this->id     = (!empty($data['id'])) ? $data['id'] : null;
     $this->name = (!empty($data['name'])) ? $data['name'] : null;
     $this->email  = (!empty($data['email'])) ? $data['email'] : null;
     $this->password  = (!empty($data['password'])) ? $data['password'] : null;     

 }


public function __set($name, $value) {
    $method = 'set' . $name;
    if (!method_exists($this, $method)) {
        throw new Exception('Invalid Method');
    }
    $this->$method($value); 
}

public function __get($name) {
    $method = 'get' . $name;
    if (!method_exists($this, $method)) {
        throw new Exception('Invalid Method');
    }
    return $this->$method();
}

 public function getArrayCopy()
 {
     return get_object_vars($this);
 }

 public function setInputFilter(InputFilterInterface $inputFilter)
 {
     throw new \Exception("Not used");
 }

 public function getInputFilter()
 {
     if (!$this->inputFilter) {
         $inputFilter = new InputFilter();

         $inputFilter->add(array(
             'name'     => 'id',
             'required' => true,
             'filters'  => array(
                 array('name' => 'Int'),
             ),
         ));

         $inputFilter->add(array(
             'name'     => 'name',
             'required' => true,
             'filters'  => array(
                 array('name' => 'StripTags'),
                 array('name' => 'StringTrim'),
             ),
             'validators' => array(
                 array(
                     'name'    => 'StringLength',
                     'options' => array(
                         'encoding' => 'UTF-8',
                         'min'      => 1,
                         'max'      => 100,
                     ),
                 ),
             ),
         ));

         $inputFilter->add(array(
             'name'     => 'email',
             'required' => true,
             'filters'  => array(
                 array('name' => 'StripTags'),
                 array('name' => 'StringTrim'),
             ),
             'validators' => array(
                 array(
                     'name'    => 'EmailAddress',
                     'options' => array(
                         'domain' => true, 
                     ),
                 ),

             ),
         ));


         $this->inputFilter = $inputFilter;
     }

     return $this->inputFilter;
 }


}

查看/ changepassword.phtml:

<?php

namespace Admin\Model;


 use Zend\Db\TableGateway\TableGateway;

 use Zend\Db\Adapter\Adapter;

 class ProfileTable
 {
     protected $tableGateway;  



 public function __construct(TableGateway $tableGateway)
 {
     $this->tableGateway = $tableGateway;

 } 

public function fetchAll($user_email)
{ 
    $resultSet = $this->tableGateway->select(array('email' =>$user_email));
    return $resultSet;     
}

public function getProfile($id)
{
    $id  = (int) $id;
    $rowset = $this->tableGateway->select(array('id' => $id));
    $row = $rowset->current('id');  
    if (!$row) {
        throw new \Exception("Could not find row $id");             
    }

    return $row;
}


 public function saveProfile(Profile $profile)
 {
     $data = array(
         'name' => $profile->name,
         'email'  => $profile->email, 
     );

     $id = (int) $profile->id;
     if ($id == 0) {
         $this->tableGateway->insert($data);
     } else {
         if ($this->getProfile($id)) {
             $this->tableGateway->update($data, array('id' => $id));
         } else {
             throw new \Exception('Profile id does not exist');
         }
     }
 } 

 }

1 个答案:

答案 0 :(得分:1)

我自己完成了这个。更改密码的答案和最佳解决方案如下:

changepassword.phtml:

<div class="jumbotron">
<h2 align="center">Change Your Password Here:</h2>

<div align="right">
<a href="<?php echo $this->url('profile');?>">View Profile</a>
</div>
<br/>

 <?php
 $form = $this->form;
 $form->setAttribute('action', $this->url('profile',
     array(
     'action' => 'changepassword',
     'id'     => $this->id,
     )
 ));
 $form->prepare();
 ?>

 <?php echo $error; ?>
 <div align="center">
 <?php
echo $this->form()->openTag($form);
 echo $this->formHidden($form->get('id')); 
echo $this->formRow($form->get('old_password'));
 echo "<br/>";
 echo $this->formRow($form->get('new_password'));
 echo "<br/>";
 echo $this->formRow($form->get('confirm_password'));
 echo "<br/>"; 

 echo $this->formSubmit($form->get('submit'));
 echo $this->form()->closeTag();
 ?>
 <a href="<?php echo $this->url('profile');?>">Cancel</a>
 </div> 

 </div>

在Profile.php中添加此代码

public function getInputFilter2()
 {
     if (!$this->inputFilter) {
         $inputFilter = new InputFilter();

         $inputFilter->add(array(
             'name'     => 'id',
             'required' => true,
             'filters'  => array(
                 array('name' => 'Int'),
             ),
         ));

          $inputFilter->add(array(
             'name'     => 'old_password',
             'required' => true,
             'filters'  => array(
                 array('name' => 'StripTags'),
                 array('name' => 'StringTrim'),
             ),
             'validators' => array(
                 array(
                     'name'    => 'StringLength',
                     'options' => array(
                         'encoding' => 'UTF-8',
                         'min'      => 2,
                         'max'      => 100,
                     ),
                 ),
             ),
         ));

          $inputFilter->add(array(
             'name'     => 'new_password',
             'required' => true,
             'filters'  => array(
                 array('name' => 'StripTags'),
                 array('name' => 'StringTrim'),
             ),
             'validators' => array(
                 array(
                     'name'    => 'StringLength',
                     'options' => array(
                         'encoding' => 'UTF-8',
                         'min'      => 2,
                         'max'      => 100,
                     ),
                 ),
             ),
         ));

          $inputFilter->add(array(
             'name'     => 'confirm_password',
             'required' => true,
             'filters'  => array(
                 array('name' => 'StripTags'),
                 array('name' => 'StringTrim'),
             ),
             'validators' => array(
                 array(
                     'name'    => 'StringLength',
                     'options' => array(
                         'encoding' => 'UTF-8',
                         'min'      => 2,
                         'max'      => 100,
                     ),
                 ),
             ),
         ));

         $this->inputFilter = $inputFilter;
     }

     return $this->inputFilter;
 }

在ProfileTable.php中添加以下功能

public function updatePassword($password,Profile $profile)
{
    $data = array( 
        'password' => md5($password), 
    ); 
     $id = (int) $profile->id;

    if ($this->getProfile($id)) 
    {
        $this->tableGateway->update($data, array('id' => $id));
    } 
    else 
    {
        throw new \Exception('Profile id does not exist');
    }  

}

在ProfileController.php中添加以下代码

 public function changepasswordAction()
{
    $this->layout("layout/layout_admin");  

    $id = (int) $this->params()->fromRoute('id', 0);
    if (!$id) {
        return $this->redirect()->toRoute('login', array(
            'action' => 'index'
        ));
    }

    // below condition is new and for back browser validation 
    if (!$this->getServiceLocator()
            ->get('AuthService')->hasIdentity()) {
        return $this->plugin(redirect)->toRoute('login', array('action' => 'index'));
    } 
    $error = ""; 
    $password="";

    // Get the Profile with the specified id.  An exception is thrown
    // if it cannot be found, in which case go to the index page.
    try {
        $profile = $this->getProfileTable()->getProfile($id);
    }
    catch (\Exception $ex) {
        return $this->redirect()->toRoute('profile', array(
            'action' => 'index'
        ));
    }


    $form  = new ProfileForm();
    $form->bind($profile);
    $form->get('submit')->setAttribute('value', 'Change');



    $request = $this->getRequest(); 



    if ($request->isPost()) {
        $form->setInputFilter($profile->getInputFilter2());
        $form->setData($request->getPost()); 

        if(($profile->password == md5($this->params()->fromPost('old_password')))AND($form->isValid())) 
        {
            if($this->params()->fromPost('new_password') == $this->params()->fromPost('confirm_password')) 
            {  
                $password=$this->params()->fromPost('confirm_password');
                $this->getProfileTable()->updatePassword($password,$profile);

                //Redirect to profile
                return $this->redirect()->toRoute('profile');
            } 
            else 
            {
                $error="<b>Error: </b>New Password and Confirm password didn't match";
            }

        } 
        else 
        {
            $error="<b>Error: </b>Old Password didn't match";
        }


    }


    return array(
        'id' => $id,
        'form' => $form,
        'error' => $error,
    );

}
相关问题