Jump to content
Larry Ullman's Book Forums

Edward

Members
  • Posts

    1115
  • Joined

  • Last visited

  • Days Won

    27

Everything posted by Edward

  1. For fixing the static pages this guide in the Yii Docs should be useful: http://www.yiiframework.com/doc/guide/1.1/en/topics.url
  2. There are some things covered on getting url's to look nice in the Yii book, in your main.php file in the config folder change to the code urlManager code to that of below in the return array. This will tidy things up for you. 'urlManager'=>array( 'showScriptName'=>false, 'urlFormat'=>'path', 'rules'=>array( '<controller:\w+>/<id:\d+>'=>'<controller>/view', '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>', '<controller:\w+>/<action:\w+>'=>'<controller>/<action>', ), ), Also make sure you have a .htaccess file in your index.php folder which should have the contents as follows: (Of course your mod rewrite engine must be on in order for the rewrite rules to work. <ifModule mod_rewrite.c> # Turn on the engine: RewriteEngine on # Do not perform redirects for files and directories that exist: RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # For everything else, redirect to index.php: RewriteRule . index.php </ifModule>
  3. http://www.larryullman.com/forums/index.php?/topic/1491-my-project-diary/page__st__40#entry11492 The code written for the 6th of December, its not final stuff just practice.
  4. Oh, what did you think of my Yii code in my practice project?
  5. I am actually really enjoying having a hack at things myself in Yii before your chapters come out. I find i learn more this way than just working through the book.
  6. Edward

    My Project Diary

    Yes you could do that check for the not null value but the actual login page on the live site would be blocked via accessRules() which could be added in the site model. So therefore the login page would be disabled for authenticated users. I just added in some nice way of thinking about the confusing return. So a way i thought of looking at this !$this->errorCode was If something is NOT TRUE it must be FALSE and If something is NOT FALSE it must be TRUE this is almost sounds like a nursery rhyme.
  7. Edward

    My Project Diary

    Antonio i saw that funny coding style you complained about last time in the UserIdentity class: do you remember return !$this->errorCode; (Can also be written as $this->errorCode == self::ERROR_NONE) if you go to CBaseUserIdentity you will find const ERROR_NONE=0; const ERROR_USERNAME_INVALID=1; const ERROR_PASSWORD_INVALID=2; So a way i thought of looking at this !$this->errorCode was If something is NOT TRUE it must be FALSE and If something is NOT FALSE it must be TRUE this is almost sounds like a nursery rhyme.
  8. Edward

    My Project Diary

    Thursday, December 6th, 2012 Got the activation page working page with basic coding for now, i need to move some of the logic code which is highlighted below into the model using a relevant method. I also used active record to pull out the model instance for the user. When i tried to use Save() to update the model instance it didn't save directly to the database, so i had to use saveAttributes to get it to work, otherwise if i am correct it was trying to save a whole record. public function actionactivate() { if(isset($_GET['x'], $_GET['y'])) { // Load up the active record model with email from $_get['x'] $user = User::model()->find('email=:email', array(':email'=>$_GET['x'])); // Redirect if activation code is already null or no record was found if ($user === null || $user->activation_code === null || $user->activation_code !== $_GET['y']) // Redirect to site index page $this->redirect(Yii::app()->user->returnUrl); } else // Redirect to site index page $this->redirect(Yii::app()->user->returnUrl); $modelUser = new User('activate'); if(isset($_POST['User'])) { $modelUser->attributes = $_POST['User']; if($modelUser->validate()) { // TODO Write model method for this code $user->username = $modelUser->username; $user->password = $modelUser->password; $user->activation_code = 'null'; $user->saveAttributes(array('username', 'password', 'activation_code')); $this->redirect(array('view','id'=>$user->id)); } } $this->render('activate',array( 'model'=>$modelUser, 'data'=> array( 'first_name' => $user->first_name, 'email' => $user->email, 'activation_code' => $user->activation_code ))); } I also worked on the login page which is now working i had to make customizations to the User_Identity Scipt class UserIdentity extends CUserIdentity { /** * Authenticates a user. * The example implementation makes sure if the username and password * are both 'demo'. * In practical applications, this should be changed to authenticate * against some persistent user identity storage (e.g. database). * @return boolean whether authentication succeeds. */ private $_id; public function authenticate() { // Load model for username and email by active record $user = User::model()->findByAttributes(array('username'=>$this->username)); if($user === null) $this->errorCode=self::ERROR_USERNAME_INVALID; else if($user->password !== $user->hashpassword($this->password)) $this->errorCode=self::ERROR_PASSWORD_INVALID; else { $this->_id = $user->id; $this->username = $user->username; $this->errorCode = self::ERROR_NONE; } return $this->errorCode == self::ERROR_NONE; } public function getId() { return $this->_id; } } Here is my LoginForm model code class LoginForm extends CFormModel { public $username; public $password; public $rememberMe; private $_identity; /** * Declares the validation rules. * The rules state that username and password are required, * and password needs to be authenticated. */ public function rules() { return array( // username and password are required array('username, password', 'required'), // rememberMe needs to be a boolean array('rememberMe', 'boolean'), // password needs to be authenticated array('password', 'authenticate'), ); } /** * Declares attribute labels. */ public function attributeLabels() { return array( 'rememberMe'=>'Remember me next time', ); } /** * Authenticates the password. * This is the 'authenticate' validator as declared in rules(). */ public function authenticate($attribute,$params) { if(!$this->hasErrors()) { $this->_identity = new UserIdentity($this->username,$this->password); if(!$this->_identity->authenticate()) // Added two messages in here as only the password textbox was going red, it was better when both were red $this->addError('username',''); $this->addError('password','Incorrect username or password.'); } } /** * Logs in the user using the given username and password in the model. * @return boolean whether login is successful */ public function login() { if($this->_identity === null) { $this->_identity = new UserIdentity($this->username,$this->password); $this->_identity->authenticate(); } if($this->_identity->errorCode === UserIdentity::ERROR_NONE) { $duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days Yii::app()->user->login($this->_identity,$duration); return true; } else return false; } }
  9. Edward

    Preference

    "Which approach you take–validation scenarios or events–is largely a matter of preference, as both will do the trick. With event handling, you are moving more of the logic out of the rules and into new methods, which can make for cleaner code." Method1: # protected/models/AnyModel.php::rules() array('date_entered', 'default', 'value'=>new CDbExpression('NOW()'), 'on'=>'insert'), array('date_updated', 'default', 'value'=>new CDbExpression('NOW()'), 'on'=>'update'), Method2: # protected/models/AnyModel.php public function beforeSave() { if ($this->isNewRecord) { $this->created = new CDbExpression('NOW()'); } else { $this->modified = new CDbExpression('NOW()'); } return parent::beforeSave(); } Edward: I started out i using Method2 to do this, but i thought method1 that you suggested using the default was much better. As in my User model i have loads of methods already and therefore trying to reduce them is a good. I also found in beforeSave and other event handling methods like this that i had to test on other scenario's rather than the predefined 'insert' and 'update'. So it just seems tidier to keep defaults like these using rules() in Method1. Just my thoughts. To Larry: I was very impressed with "Working with Models" i have learned quite a lot of extra simplifying coding tips just reading through that. Yii should of had something like this a long time ago. I don't think it would be a bad idea for you to write a eBook on how to use ZendFramework 2 because they have nothing useful like this either.
  10. I would say that sums my question up. It was just looking so that you may finish the book in June 2013 or something like that. But if you can make it by March or April even better. I have been doing some stuff myself taking a few steps forward but then later having to come back two steps to make three steps forward. The sooner your stuff is done the sooner we know what is right and what is wrong. Only you can confirm this with the owner of Yii.
  11. Technique meaning method used by adding the extra hidden value into the forum that's all. Thanks
  12. When i comes to PHP for me i don't really have a choice with it but to learn it along with Javascript and MySQL database software. What isn't run by PHP today? I have only used Pascal, C, Assembly language in the past and was really surprised by how easy PHP was to learn. PHP is loosely type so like in C where you had to state what type of variable you were declaring, integer, string, float etc and had to do manipulations with the same type of variable otherwise errors would be thrown. I am new to PHP as you know so i haven't really had my fair share of real system errors so can't comment on that. But i guess i like PHP because like you say it can get the job done, and that's what you get money for. I don't mean to say its all about money as i do enjoy working on code its quite satisfying when things work out. PHP for me is like waving a magic wand. Sorry i am unable to comment on those other language's i am just sticking to the point in getting this one wrapped up for my project. Another point is that all the main frameworks are written for use with PHP, Zend, CakePHP, Codeignitor, Yii, Symphony etc. Then you have Drupal and Joomla. There are just more resources available for it and it makes PHP more approachable. As with regards to bashers there will always be people on the opposite sides, so it doesn't really matter, it just depends which one works out for you. Well its time for me to get back to my Wand!
  13. Have you tried this technique does it work? Would be very useful if it does!
  14. Edward

    My Project Diary

    Made a cock up with my with my actionactivate script, found easier ways to do this, please don't anyone try the above.
  15. Thanks for writing such a lot, yeah i guess you have a point there separating property names from active record or database names. I Agree with what you are saying, i will do my best with naming conventions, i would like to build more to see what happens as now i don't have so much experience like yourself. CSS is somewhat similar you have to pick good clear names and know how to separate for different pages in larger projects. Those methods that you mentioned i will be working on those soon in the user model() i know i have to move the logic into the model. I just want to see that i can get the points in Yii working first of all then i will concentrate more on tidying up. Like you i think of coding before and even while i am at it, its always in my mind this stuff such a lot of it.
  16. Edward

    My Project Diary

    Saturday, December 1st, 2012 I can't believe its December already, its like summer here i hadn't realized the time has gone so quickly. I was working on Yii yesterday but didn't get a smooth run, this will be the last time i say this but i think the Yii documentation sucks. They have stuff all over the place, its hard trying to figure out or get basic examples of some basic php stuff and how to do it in Yii. I had a lot of success working how to do things in Yii through the Yii errors and debugging. In the last two days in the time i had i was working on my activation page a bit like the one i done earlier in my practice site but this time i will add in more security checking. As i understand we don't need to use real_escape_string() as PDO does this for us and whatever you use DAO, Query Builder or Active record it will be done as its all run on PDO (PHP Data Objects). The code below is not completely finished yet and also i know i need to move some of this code logic from the controller into the model. I am still waiting to see how Larry does this in his chapters, so now i know there is not also "Performance Tuning" in Yii, there is "Larry Tuning", this is a new Coding terminology i have come up with today. Okay here is the code and today was the first time i used Yii Query Builder, public function actionactivate(){// TODO Get the Activation page completedif(isset($_GET['x'], $_GET['y'])){// SQL "SELECT id, first_name, activation_code FROM user WHERE email='$_GET['x']"$row = Yii::app()->db->createCommand(array( 'select' => array('id', 'first_name', 'activation_code'), 'from' => 'user', 'where' => 'email=:email', 'params' => array(':email'=>$_GET['x']),))->queryRow();// Redirect if activation code is already null or no rows were found where sql will return falseif ($row===false || $row['activation_code']===null) {// Redirect to site index page$this->redirect(Yii::app()->user->returnUrl);}} else {// Redirect to site index page$this->redirect(Yii::app()->user->returnUrl);}$modelUser = new User('Activate');$this->render('activate',array('model'=>$modelUser, 'data'=> array('first_name' => $row['first_name'],'email' => $_GET['x'],'activation_code' => $_GET['y'])));} ill will finish off the post part tomorrow and Monday. I have to work on this part this can be done with routes.
  17. The style of coding in Yii seems to be if (etc) { } as opposed to if (etc ) { } I see in your tuturiols Larry you prefer the 2nd style which i have come to prefer myself but what should we do in Yii, use our conventional way which mean we will have mixed code or just use the new style? (Or do we change all the parentheses in Yii to make them look nice, lol) Also another thing that bugs me is, is say saving things in the database like for instance first_name, we use the underscore between the two words. The thing is when we make properties in Yii as its OOP and we are using classe we use Camel Case for our properties, so if we declared first_name as a property it would be ugly rather than the correct way of firstName. I find i can get confused when passing over data from a controller to view and thought it might be a good idea to rename the database columns with Camel Case. So firstName, lastName, activationCode etc, what do you think of this or others here who may have views?
  18. Larry what's your time plan per getting one chapter done up to the putting it all together examples which i would suspect will take longer?
  19. Antonio do you have the actual resources for the full list of postal info for each country? I also think trying to determine database structure's now is pretty much impossible that is depending on the size of your website. Once there is more data and once you know exactly what queries you need and then how to limit stress on particular tables then you would really know how to set everything up correctly. That's why again done is better than perfect for the time being.
  20. Why don't you just show us the rules() method code for the User model, then it might be possible to work out what is going on? An email validator can be declared like this using the email alias keyword. array('email', 'email', 'checkMX'=>true, 'message'=>'Please enter a valid email!'), checkMX Checks to see if this is a valid email domain.
  21. Edward

    My Project Diary

    Thursday, November 29th, 2012 protected function beforeSave() { if ($this->isNewRecord) { // Set registration date and last activity $this->registration_date = $this->last_activity = new CDbExpression('NOW()'); // Create the activation code: $this->activation_code = md5(uniqid(rand(), true)); // Set correct birthday format (MM/dd/yyyy) -> (YYYY-MM-DD) $this->birthday = date("Y-m-d", strtotime($this->birthday)); } else { // Set last activity if account updated $this->last_activity = new CDbExpression('NOW()'); } return parent::beforeSave(); } Thanks to Larry's Chapter on models i got the beforeSave() method to work in the model class, from the website the function failed to work. As you can see above i set the account activate code here which will be a md5 32 characters long string which will be used to validate an account. I am saving date of birth or birthday in my records when i first tried this on yii it didn't work and saved 0000-00-00 so i had to convert the Yii formatted date over to the SQL YYYY-MM-DD format for it to save. I have to send an email to the user with a link to which the click to come to the activate page but there is no documentation i could find on the YiiFramework help explaining how to do this so i have left that bit for now. I would be implementing this code into the afterSave() method in the model class once i know how to do it. Right now i am off to read more on Larry's model chapter good bye for now.
  22. Edward

    My Project Diary

    Yes it is pretty cool, the problem is though i have a transaction involved there so I am not sure about using afterSave() for this. Remember what facebook said though done is better than perfect. I will starting the Yii Application development book again next week as i can see that does provide some extra tips. You know how you get brain freeze when you drink an ice drink too quickly, well i get the opposite when trying to figure this out alone, i call it brain burn. Reading some extra books and not just trying to work it out myself will ease on the real coding. About testing, Ive done unit testing before with phpunit but now i am starting to see the importance of these unit tests. They are useful as they can be stored in the framework and can also save time. Ive wasted a lot of time in the last few days re-entering data into a big form. The Yii application Development book is real heavy on unit tests from the beginning of the book, i think that book is actually pretty good but i really people with more experience would understand the real benefit of it.
  23. Edward

    My Project Diary

    Wednesday, November 28th, 2012 I have been working on my Yii user controller and added in an actionNew() method, this part of code is for adding a user and there address details to the database. For some reason the foreign key constraint ON DELETE CASADE ON UPDATE NO ACTION, failed to work and stated that i was unable to add or update a child record. I will work on this problem tomorrow. As for the code below it works successfully without the constraint for the time being. public function actionNew() { $modelUser = new User('Register'); $modelAddress = new Address; if(isset($_POST['User'], $_POST['Address'])) { $modelUser->attributes = $_POST['User']; $modelAddress->attributes = $_POST['Address']; $modelUser->validate(); $modelAddress->validate(); $transaction = Yii::app()->db->beginTransaction(); if($modelUser->save()) { $modelAddress->user_id = $modelUser->id; if($modelAddress->save()) { $transaction->commit(); $this->redirect(array('view','id'=>$modelUser->id)); } else $transaction->rollBack(); } } $this->render('new',array( 'model'=>$modelUser,'model2'=>$modelAddress, )); }
×
×
  • Create New...