Tag Archives: yii

Yii PNotify Extension

I have been using the PNotify extension in my Yii project and have had a good experience with it. PNotify is a JQuery extension that you can use to show notifications for you site. I use it when a user saves a form or deletes a record. Any interactions that require some type of response from the server. The Yii extensions makes it even easier to use this JQuery plugin. When you install the plugin all you have to do as add it to all your pages you are going to be using it on. For my project I added it to the layouts header file. You can add it to whatever page works best for you site


<?php $this->widget('application.extensions.PNotify.PNotify', array('flash_messages_only' => true,)); ?>

If you need to use it as a ajax response you can do that also. Since you included it as part of the header the javascript will already be available on the page. You can simply do this.


parent.$.pnotify({'type':'success','title':response.title,'text':response.message});

As you can see this extension is very easy to use and can add a nice message module to your interface. I encourage you to check it out as it looks better than your typical popup or flash notification.

Yii Automating deployment without capistrano

Automating tasks and routines is very important. If you are doing deployments manually you really need to consider making an automated way of doing it. A good tool that is Ruby based is  capistrano. The one thing I noticed about capistrano though was the tool was kind of heavy. I wanted something a little more lightweight that I understood the entire process. So even though capistrano would have got the job done I didn’t need such a heavy tool. So I decided to create my own tool. This is just a single PHP script that you could store in your commands directory. Then you just execute it.


php commands/release_test.php

You could also pass in an environment variable if you don’t want to have a separate command for each environment. For me I wanted it as a separate command so I didn’t have to think about it on release. Here is the script in detail hopefully it’s useful to other Yii projects.


<?php
 // This is a simple script that can be used to release code to the test environment

&nbsp;

$server_location = ‘[234.343.343.343]’;
 $env = ‘[testing]’;
 $server_username = ‘[USERNAME]’;
 $production_location = ‘[PRODUCTION_LOCATION] i.e. /Users/whatever/location…’;
 $project_assets_location = ‘[ASSETS]’;

$git_upstream_name = ‘[upstream]’;
 $git_branch_name = ‘[branch_name]’;

// connect to the server
 $connection = ssh2_connect($server_location, 22);

echo “Enter password: “;
 $password = preg_replace(’/\r?\n$/’, ‘’, `stty -echo; head -n1 ; stty echo`);
 echo “\n”;

ssh2_auth_password($connection, $server_username, trim($password));

// update the remote repository
 $updateResponse = ssh2_exec($connection, ‘cd ‘.$production_location.’; git remote update’);
 stream_set_blocking($updateResponse, true);
 $updateResponseOutput = stream_get_contents($updateResponse);
 echo $updateResponseOutput.”\n”;

// pull in the latest code
 $pullResponse = ssh2_exec($connection, ‘cd ‘.$production_location.’; git pull ‘.$git_upstream_name.’ ‘.$git_branch_name);
 stream_set_blocking($pullResponse, true);
 $pullResponseOutput = stream_get_contents($pullResponse);
 echo $pullResponseOutput.”\n”;

// run the migrations
 $migrations = ssh2_exec($connection, ‘YII_ENVIRONMENT=’.$env.’ ‘.$production_location.’/yiic migrate —interactive=0’);
 stream_set_blocking($migrations, true);
 $migrationsOutput = stream_get_contents($migrations);
 echo $migrationsOutput.”\n”;// check to see if we want assets rebuild
 echo “Do you want to rebuild assets? Type ‘yes’ to rebuild assets: “;
 $handle = fopen (“php://stdin”, “r”);
 $line = fgets($handle);
 if (trim($line) == ‘yes’) { $cleanAssets = ssh2_exec($connection, ‘rm -r ‘.$project_assets_location.’/*’); stream_set_blocking($cleanAssets, true); $cleanAssetsOutput = stream_get_contents($cleanAssets); echo $cleanAssetsOutput.”\n”;
 }
 // close the connection

// exit the ssh2 connection
 ssh2_exec($connection, ‘exit’);

Frameworks

When I started out my development career I thought the idea of a framework was stupid. If I already know the language then what was the point in learning a framework. It’s just another thing I have to know about. At the time my mindset was I can do anything the framework can do. Yeah I might have to spend the time coding it up but at least I understood it at the end. Also a lot of the core functionality you need when you are creating a site is built into the language itself. For example PHP has all of the date functions one would need. At the time PHP wasn’t really not an object oriented language either so there wasn’t frameworks built for it when I started my career. When PHP was enhanced to support objects they kind of came over time. At that time I was in the mindset that I didn’t want to learn a custom framework. Since I already was doing everything myself. Then it all changed when I worked at a company who started working with a framework. After struggling for a little bit while first learning it I am glad I spent the time.

The main benefit I see from a framework is consistency. If you start with a framework and follow the frameworks pattern’s your code base will be consistent. It makes adding new developers onto the team way easier also. You are able to point them to documentation already created. Also that documentation is always up to date. If you are rolling your own framework most of the time documentation is the last step or in most cases doesn’t get done. Not only will you have consistency but you will not trap yourself into a bad pattern. If you choose a popular framework you know it has been tested on a wide variety of applications. If it can handle all of those applications you know it can handle yours. Unless you are trying to do something way out there.

Another benefit from using a framework is you get to use the communities code. Most frameworks at least the good ones have some form of extensions. They are called something different with each framework. For example in the yiiframework they are called extensions while in ruby they are called gems. These extensions allow you to easily pull in code and modify it to your needs. You save yourself a ton of time by not having to write that datatable helper or the audit helper. A lot of this is already done. Why not use something you know is working for others? You can then focus your time on the important things. No need to reinvent the wheel.

There can be some drawbacks to using a framework. One thing we face these days is frameworks are becoming to heavy. They have a ton of code that projects may not use. Also they kind of force you into a certain way of doing things. You can always code your way out of it but it might take you extra time. Another drawback is if you fall behind on major versions. If you fall behind upgrading can be a big pain. If you don’t upgrade to the latest version you could have security issues or extension compatibility issues.

At the end of the day you want to get your website up and running super fast. When you have a framework to start with you can have a simple application up and running in minutes. Also you don’t want to spend you time writing common code that is already been done a million times by other developers. Instead you want to focus on creating the customized aspects of your website or product. Even though it does take a little investment learning the framework it’s well worth the time. After you learn one framework you will see the pattern throughout other frameworks will be very similar.

Yii framework custom methods inside datatable row

I have been using the  edatatables extension from the yiiframework for a while now. I have noticed that you can do a ton of things with it. These things take very little effort. The extension is very powerful and was well done. Recently I ran into a situation that wasn’t apparent to me right away on how to implement a column with customized HTML. I wasn’t able to use the default column_name value since I needed to format it. The first thing I did was create a method inside the given model that would return the HTML. In the Yii framework models cannot call partials so I had to have the HTML within that models method. To me this looked out of place and felt dirty. Being a pragmatic programmer I decided to look into a better solution. I stumbled upon this solution while researching this. This solution did not seem to be common so I think this post could be beneficial to others.

The solution was to call an internal method within that controller and pass in the given data row. Through the internal function I am then able to render a partial and pass that HTML back to the actual row. When I called render partial in Yii I add the true parameter at the end so it doesn’t render it real time. Instead keeping it in a variable to return. This allowed me to remove the method from the model and move that HTML logic into the view layer. The code below show my implementation that involved adding the custom array to the columns definition and create an internal method to be called.


$columns = array( ‘column1’, ‘column2’, ‘column3’, array( ‘header’ =>         ‘Column 4’, ‘class’ => ‘EDataColumn’, ‘sortable’ => ‘false’, ‘value’ =>         array($this, ‘_latestPrices’), ‘type’ => ‘html’, ),
 );

protected function _partialViewBeingCalled($data, $row) {

$result = $this->renderPartial(’../shared/_myPartial’,array( ‘Data’ => $data, ), true);

return $result;

}

As you can see the solution is very simple. The hardest part was figuring out how the datatable would call the internal method while passing the data. After those updates I now have a clean solution that I can feel satisfied with.

PHP Yii and Ruby on Rails Active Record

I have been using the Yii Framework for over two years now and have been using the Ruby on Rails framework for around the same time period. I have done various projects in each and thought I would share my experience. The scope of this post will just be the differences between active records. It will not go into other details about the two frameworks. The purpose of this post is also not to debate which one is better. The purpose is to simply give the differences between the two and show the capabilities of each. This will only cover some features of each it will not include all of the features.

Ruby on Rails

Ruby on Rails has a powerful active record implementation. For example if you want to find something by it’s primary key. You would write something like Model.find(:id). This would then return an active record object with the properties of that single item. You can also add multiple conditions by simply by calling the where method. It would look similar to this Model.where(id: 10, text: ‘whatever’). This will then return a set of active record objects instead of just the single object the find would return. If you know there will only be one result you can simply do .first to get the result back.

Another part of active record is scopes. You can create scopes within a model and call them directly instead of having to write the where conditions over again. So if you need to write a query multiple times it’s a sign that you should create a scope instead. A scope is just defined in the model and can use lambda to pass in dynamic parameters.

Associations is a big part of Rails or any framework for that matter. In Rails associations are very simply and if it’s a simple relationship is dead simple. For example a post can have many comments. At the top of your post model you would add in a has_many :comments. As long as the keys match up that’s all you have to do. You can also do more advanced relationship mappings to.

PHP Yii

Yii has a powerful active record implementation also but uses a different implementation method. For example if you want to find a record by it’s primary key you can simply do ModelName::model()->findByPk(‘key’);. That will return a single active record object back. If you need to do more advanced queries you can do it in two ways. The first is to call the findByAttributes method. That would looks something like ModelName::model()->findByAttributes(array(‘a’ => ‘test’, ‘b’ => ‘whatever’));. That implementation will also just return a single active record object back if found. For advanced queries you can also create a CDbCriteria object with the criteria generated. When you look at the documentation you will see the various attributes you can set. After setting the object you can then simply call your query like this ModelName::model()->find(CDbCritieriaObject);.

Yii also has support for scopes. Similar to Rails Yii scopes are also defined in that specific model. A scope is Yii is basically a short cut to creating the CDbCriteria object. You will be passing in very similar parameters. It’s just as powerful as CDbCriteria also so you can do advanced queries without much of an issue.

Associations are also a big part of the Yii framework. They take a little more code than the Rails framework though. For example to do a has_many relationship you have to define it like this.


public function relations() {

return array('relationshipName' => array(

self::HAS_MANY, 'RelationshipModelName', 'RelationshipModelNamePk'

),

),

);

 

As you can see it takes a little bit more code to define them. These can be auto generated though through the Gii tool. So they are not as big of a deal to code up as 99% of the work is done if not 100%.

Those are some of the difference between the two of them. There are a lot more differences and this only covers the surface. The goal of this post is really to just share that each can do very similar things just in different ways. If you end goal is to get something up and running I feel that both frameworks can handle that. It comes down to a preference between Ruby and PHP.