Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [skrypt] Kohana ocena kodu
Forum PHP.pl > Inne > Oceny
bladeer
Witam, Uczę się kohany, i proszę was o ocene kodu napisanego właśnie na kohanie. Wszelaka krytyka wskazana wink.gif
Skrypt służy do logowania, rejestracj, zmiany hasła itp dla małej wyszukiwarki firm, praca robiona na praktyki szkolne.

Kontroler:
  1. <?php
  2.  
  3. defined('SYSPATH') or die('No direct script access.');
  4.  
  5. class Controller_User extends Controller_Layout
  6. {
  7.  
  8. public function action_index()
  9. {
  10.  
  11. }
  12.  
  13. public function action_login()
  14. {
  15. // If user already signed-in
  16. if (Auth::instance()->logged_in() != 0) {
  17. //redirect to the user account
  18. HTTP::redirect('index/index');
  19. }
  20.  
  21.  
  22. $this->template->content = View::factory('user/login');
  23. if ($this->request->post()) {
  24. Helper::filter_post($this, array(
  25. 'username',
  26. 'password',
  27. 'remember'
  28. ));
  29.  
  30. $user = ORM::factory('User');
  31. $validation = $user->validate_login($this->request->post());
  32.  
  33. if ($validation->check()) {
  34. $user = Auth::instance()->login(
  35. $this->request->post('username'), $this->request->post('password'), $this->request->post('remember')
  36. );
  37. if ($user) {
  38. HTTP::redirect('index/index');
  39. } else {
  40. $this->template->errors = array('Niepoprawny login lub hasło');
  41. }
  42. } else {
  43. $this->template->errors = $validation->errors('register');
  44. }
  45. }
  46. }
  47.  
  48. public function action_logout()
  49. {
  50. // Log user out
  51. Auth::instance()->logout();
  52. // Redirect to login page
  53. HTTP::redirect('user/login');
  54. }
  55.  
  56. public function action_register()
  57. {
  58. // If user already signed-in
  59. if (Auth::instance()->logged_in() != 0) {
  60. //redirect to the user account
  61. HTTP::redirect('user/profil');
  62. }
  63.  
  64.  
  65. if ($this->request->post()) {
  66. Helper::filter_post($this, array(
  67. 'username',
  68. 'email',
  69. 'username',
  70. ));
  71.  
  72. $user = ORM::factory('User');
  73. $validation = $user->validate_register($this->request->post());
  74. if ($validation->check()) {
  75.  
  76. $user->username = $this->request->post('username');
  77. $user->password = $this->request->post('password');
  78. $user->email = $this->request->post('email');
  79. $user->save();
  80.  
  81. $login_role = new Model_Role(array('name' => 'login'));
  82. $user->add('roles', $login_role);
  83.  
  84. Helper::notice('Rejestracja ukończona. Teraz możesz się zalogować');
  85. } else {
  86. $this->template->errors = $validation->errors('register');
  87. }
  88. }
  89.  
  90. $this->template->content = View::factory('user/register');
  91. }
  92.  
  93. public function action_profil()
  94. {
  95. Helper::chceck_login();
  96.  
  97. $this->template->content = View::factory('user/profil');
  98. }
  99.  
  100. public function action_changepass()
  101. {
  102. $user = new Model_User;
  103. $validation = $user->validate_change_pass($this->request->post());
  104. if ($validation->check()) {
  105. //zmieniamy hasło
  106. $user = ORM::factory('User', Auth::instance()->get_user()->id);
  107. $user->password = $this->request->post('password');
  108. $user->save();
  109.  
  110. $user->saved() ? Helper::notice('Hasło zostało zmienione') : Helper::notice('Błąd danych. Hasło nie zostało zmienione') ;
  111. } else {
  112. //jeśli validacja się nie powiodła , uruchamiamy kotroler profilu.
  113. //Wysyłamy do niego także informacje o błędach
  114. $this->template->errors = $validation->errors('change_pass');
  115. $this->action_profil();
  116. }
  117. }
  118.  
  119. public function action_changeemail()
  120. {
  121. $user = new Model_User;
  122. $validation = $user->validate_change_email($this->request->post());
  123. if ($validation->check()) {
  124. //jeśli wszystko przebiegło ok, zmieniamy email
  125. $user = ORM::factory('User', Auth::instance()->get_user()->id);
  126. $user->password = $this->request->post('email');
  127. $user->save();
  128.  
  129. $user->saved() ? Helper::notice('Email został zmieniony') : Helper::notice('Błąd danych. Email nie został zmieniony') ;
  130.  
  131. } else {
  132. $this->template->errors = $validation->errors('change_email');
  133. $this->action_profil();
  134. }
  135.  
  136. }
  137.  
  138. }


Model: (wydaje mi się że nie napisałem go poprawnie , i w normalnej aplikacju było by to nie do przyjecia, ale nie mam pomysłu jak to "unormalnić")
  1. <?php
  2.  
  3. class Model_User extends Model_Auth_User
  4. {
  5.  
  6. protected $rules_register = array(
  7. 'username' => array(
  8. array('not_empty'),
  9. array('min_length', array(':value', 3)),
  10. array('max_length', array(':value', 48)),
  11. array('regex', array(':value', '/^[-\pL\pN_.]++$/uD')),
  12. array('Model_User::check_unique', array('username', ':value')),
  13. ),
  14. 'email' => array(
  15. array('not_empty'),
  16. array('min_length', array(':value', 3)),
  17. array('max_length', array(':value', 127)),
  18. array('email'),
  19. array('Model_User::check_unique', array('email', ':value')),
  20. ),
  21. 'email_confirm' => array(
  22. array('matches', array(':validation', ':field', 'email')),
  23. ),
  24. 'password' => array(
  25. array('not_empty'),
  26. array('min_length', array(':value', 3)),
  27. array('max_length', array(':value', 48)),
  28. ),
  29. 'password_confirm' => array(
  30. array('matches', array(':validation', ':field', 'password')),
  31. ),
  32. );
  33.  
  34. protected $rules_login = array(
  35. 'username' => array(
  36. array('not_empty'),
  37. array('min_length', array(':value', 3)),
  38. array('max_length', array(':value', 48)),
  39. array('regex', array(':value', '/^[-\pL\pN_.]++$/uD')),
  40. ),
  41. 'password' => array(
  42. array('not_empty'),
  43. array('min_length', array(':value', 3)),
  44. array('max_length', array(':value', 48)),
  45. ),
  46. 'email' => array(
  47. array('not_empty'),
  48. array('email'),
  49. )
  50. );
  51.  
  52. public function validate_register($postvalues)
  53. {
  54. $array = Validation::factory($postvalues)
  55. ->rules('username', $this->rules_register['username'])
  56. ->rules('email', $this->rules_register['email'])
  57. ->rules('email_confirm', $this->rules_register['email_confirm'])
  58. ->rules('password', $this->rules_register['password'])
  59. ->rules('password_confirm', $this->rules_register['password_confirm'])
  60. ;
  61.  
  62. return $array;
  63. }
  64.  
  65. public function validate_login($postvalues)
  66. {
  67. $array = Validation::factory($postvalues)
  68. ->rules('username', $this->rules_login['username'])
  69. ->rules('password', $this->rules_login['password'])
  70. ;
  71.  
  72. return $array;
  73. }
  74.  
  75. /**
  76.   * validacja zmiany hasła.
  77.   * @param array $postvalues
  78.   */
  79. public function validate_change_pass($postvalues)
  80. {
  81. $array = Validation::factory($postvalues)
  82. ->rules('password_old', $this->rules_register['password'])
  83. ->rule('password_old','Model_User::check_pass')
  84. ->rules('password', $this->rules_register['password'])
  85. ->rules('password_confirm', $this->rules_register['password_confirm'])
  86. ;
  87.  
  88. return $array;
  89. }
  90.  
  91. /**
  92.   * validacja zmiany emaila
  93.   * @param type $postvalues
  94.   */
  95. public function validate_change_email($postvalues)
  96. {
  97. $array = Validation::factory($postvalues)
  98. ->rules('password_email', $this->rules_register['password'])
  99. ->rule('password_email','Model_User::check_pass')
  100. ->rules('email',$this->rules_login['email'])
  101. ->rule('email_confirm','matches',array(':validation', ':field', 'email'));
  102. ;
  103.  
  104. return $array;
  105. }
  106.  
  107. public static function check_unique($column, $value)
  108. {
  109. // Check if the username already exists in the database
  110. return !DB::select(array(DB::expr("COUNT($column)"), 'total'))
  111. ->from('users')
  112. ->where($column, '=', $value)
  113. ->execute()
  114. ->get('total');
  115. }
  116.  
  117. /**
  118.   * Sprawdza czy podane hasło jest zgodne z hasłem
  119.   * aktualnie zalogowanego usera
  120.   * @param string $pass Nie zhashowane hasło
  121.   */
  122. public static function check_pass($pass)
  123. {
  124. $pass_hash = Auth::instance()->hash_password($pass);
  125. return ( Auth::instance()->get_user()->password == $pass_hash) ? true : false ;
  126. }
  127.  
  128. }
  129.  


Funkcja Helper::filter_post
  1. /**
  2.   * Filtruje liste zmiennych z post
  3.   * @param object $controller
  4.   * @param array $list
  5.   */
  6. static public function filter_post($controller,$list)
  7. {
  8. foreach ($list as $value) {
  9. $controller->request->post($value, Helper::filter($controller->request->post($value)));
  10. }
  11. }
Euzebio11
Szczerze mówiać wyglada całkiem całkiem ok smile.gif na pewno jest to twój pierwszy skrypt questionmark.gif
phpion
Jest bardzo fajnie, ale można się przyczepić:
1. Może warto przypisać Auth::instance() do składowej kontrolera? Wówczas odwoływałbyś się do $this->auth zamiast każdorazowo wzywać instancję klasy.
2. Auth::logged_in() zwraca boola, więc możesz sprawdzać === TRUE zamiast != 0.
3. Po przejściu walidacji operujesz na danych z $this->request->post(). Sugerowałbym na $validation->as_array(). W KO3 nie jest to w sumie konieczne, ale w KO2 już tak (z racji filtrów). Może to moje przyzwyczajenie z KO2, ale wolę działać na danych, które faktycznie zostały sprawdzone (czyli z obiektu Validation, a nie Request).
4. Wszystkie komunikaty tekstowe proponuję przepuszczać przez __(). W przypadku konieczności tłumaczenia softu na inny język nie musisz dotykać kontrolerów.
5. W metodzie action_changeemail() masz błąd:
  1. $user->password = $this->request->post('email'); // zmieniasz hasło czy email? :)

6. Po poprawnym wysłaniu formularza i zapisaniu danych powinieneś dokonać przekierowania użytkownika na ten sam adres żeby uniknąć ponownego przesyłania formularza przy odświeżeniu strony.
7. Twój model jest całkiem OK, podoba mi się wydzielenie osobnych metod walidacyjnych dla różnych przypadków, a nie kombinowanie z jedną metodą.
8. Metoda check_unique może być napisana wydajniej (zamiast COUNT() robisz SELECT 1 FROM... i ograniczasz na LIMIT 1 - jeśli w wyniku dostaniesz jakikolwiek rekord (1) to znaczy, że user istnieje).

Generalnie: fajnie smile.gif
bladeer
Ok dzięki za opinie wink.gif co do funkcji Helper::notice to ona poprostu przekierowywuje na strone index/notice i wyświetla templatke z podanym w parametrze textem. Dzięki za znaleziony błąd.
Nie jest to mój pierwszy skrypt, wcześniej pisałem pod kohaną ale szkoda pokazywać tego kodu. Walidacja tam praktycznie nie istniała.

PS: Ok to zobaczymy co jeszcze powie mój "szef" ;p
wujek2009
Nie mogę rozgryźć funkcji helpera - filter_post a dokładniej zapisu: Helper::filter - to jest jakaś nowa funkcja z K3.3? Filtrowanie ogólnie w modelu już można zrobić przykład z Auth (ORM):
  1. /**
  2. * Filters to run when data is set in this model. The password filter
  3. * automatically hashes the password when it's set in the model.
  4. *
  5. * @return array Filters
  6. */
  7. public function filters()
  8. {
  9. return array(
  10. 'password' => array(
  11. array(array(Auth::instance(), 'hash'))
  12. )
  13. );
  14. }


Zakładam, że Twoje filtrowanie polega na usunięciu zbędnych znaków, pustych spacji, itd.
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.