Tuesday, July 10, 2012

How to make a symlink in Windows 7


  1. open cmd (as an admin)
  2. type:
mklink /d linkpath targetpath

example:

mklink /d c:\easytoremember c:\users\neil\local\applicationdata\temp\hardtoremember

Monday, April 16, 2012

on Database Trees

This is more a note to myself, but it looks like the best tree option in a database is Recursive Query, at least in Postgres, which supports the WITH clause.

Closure Table is the next best option.

Sunday, April 15, 2012

Optimistic Concurrency Control with Yii's Activerecord

Here's how to do Optimistic Concurrency Control with Yii's ActiveRecord:
class OCCActiveRecord extends CActiveRecord{

  public $checksum = null;

  public function afterFind(){

    /* get a checksum of all the attribute values after reading a record from db */

    $this->checksum = md5(implode('', $this->getAttributes(false)));

    parent::afterFind();
  }

    public function rules(){

/* use an exist validator to make sure that a record with the same checksum is still in db. if it's been modified, then checksums will be different */

 return array(
     array('id', 'exist', 'message'=>'This record was modified after you read it', 'on'=>'update', 'criteria'=>array('condition'=>'md5(concat('.implode(',',$this->attributeNames()).'))=:checksum', 'params'=>array('checksum'=>$this->checksum)))
 );
    }

}
Just a rough sketch, but you get the idea.

You could also modify this to be a behavior. Works only with MySQL AFAIK.

Table Inheritance with Yii ActiveRecord

Need to use Table Inheritance with ActiveRecord? Here's how:

This is Single Table Inheritance only.

Imagine that you want People contacts and Organization contacts. You don't want to keep them in different tables, as sometimes you sell to people, and sometimes you sell to organizations, and you want to keep a single (foreign) key to the party that you sold to.

We will create a class called Party, with subtypes Person and Organization. They will share some of Party's rules and relationships.

Here is the database schema:

CREATE TABLE `tbl_party` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `type` char(1) NOT NULL comment 'p=person,o=organization',
 `name` varchar(255) NOT NULL comment 'surname if a person',
 `given_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ;

and here is the model code:

class Party extends CActiveRecord {

    public static function model($className=__CLASS__){
 return parent::model($className);
    }

    public function tableName(){
 return 'tbl_party';
    }

    

    public function relations(){
 return array(
     
 );
    }

    public function rules(){
 return array(
     array('name,type','required'),
     array('type','in', 'range'=>array('o','p'))
 );
    }
}

class Person extends Party {

    /* this is required for subtypes */
    public static function model($className=__CLASS__){
 return parent::model($className);
    }

    public function defaultScope(){
        /* only read Parties that are People */
 return array(
     'condition'=>"type='p'"
 );
    }

    public function relations(){
        /* combine parent and own relations. can have 'People' only relations  */

 $parentRelations = parent::relations();

 $myRelations = array(

 );

 return array_merge($myRelations, $parentRelations);
    }

    public function rules(){
        /* combine parent and own rules */

 $parentRules = parent::rules();

 $myRules = array(
     array('type', 'default', 'value'=>'p'), /* set type to Person */
     array('type', 'in', 'range'=>array('p')), /* allow only Person type */
     array('given_name', 'required') /* new rule for this subtype only */
 );

 /* you want to apply parent rules last, delete them here if necessary */
 return array_merge($myRules, $parentRules);
    }

}

class Organization extends Party {

    public static function model($className=__CLASS__){
 return parent::model($className);
    }

    public function defaultScope(){
 return array(
     'condition'=>"type='o'"
 );
    }

    public function relations(){
 $parentRelations = parent::relations();

 $myRelations = array(
     
 );

 return array_merge($myRelations, $parentRelations);
    }

    public function rules(){
 $parentRules = parent::rules();

 $myRules = array(
     array('type', 'default', 'value'=>'o'),
     array('type', 'in', 'range'=>array('o'))
 );

 /* you want to apply parent rules last. delete them if necessary */
 return array_merge($myRules, $parentRules);
    }
}

Thursday, February 9, 2012

Database Notes

Wanna build your schema online and share?


Wanna test your SQL query online and share?


This might come in handy for you, if you are struggling with a SQL query:


If you don't fully understand JOINs:


Wanna hot-backup your InnoDB database?

Percona XtraBackup (open source)

Need to recover a corrupt InnoDB table?


Need to generate massive test data?

Benerator

Want to Validate your SQL?

Mimer SQL Validator



Random:
  1. if you want decent full-text search, choose PostgreSQL over MySQL, as MySQL doesn't support free-text search at the same time as foreign keys and transactions.
  2. Set your database to use the UTC timezone




Wednesday, November 23, 2011

How to read a JSON POST with Yii, and save it to the database

Let's say you are sending a json-encoded object to your create action, and want to save it in your database. here's how:

public function actionCreate() {
 
//read the post input (use this technique if you have no post variable name):
  $post = file_get_contents("php://input");

  //decode json post input as php array:
  $data = CJSON::decode($post, true);

  //contact is a Yii model:
  $contact = new Contact();

  //load json data into model:
  $contact->attributes = $data;
//this is for responding to the client:
  $response = array();

  //save model, if that fails, get its validation errors:
  if ($contact->save() === false) {
    $response['success'] = false;
    $response['errors'] = $contact->errors;
  } else {
    $response['success'] = true;
    
    //respond with the saved contact in case the model/db changed any values
    $response['contacts'] = $contact; 
  }

  //respond with json content type:
  header('Content-type:application/json');
  
//encode the response as json:
  echo CJSON::encode($response);

  //use exit() if in debug mode and don't want to return debug output
  exit();
}

Friday, October 28, 2011

Abandoning Jquery and Server-Generated HTML, moving to ExtJS + Yii backend

Our team wasted far too long trying to get our web app working with jQuery. Finally we discovered the joys of ExtJS 4, and are moving all development there.

Still using Yii as the backend for its nice models and controllers, as well as RBAC.

Saturday, August 20, 2011

Which databases does Yii support?

Yii uses PDO, which is good, as it supports parameters, which can help to prevent SQL injection attacks.

As of Yii 1.1.8, it supports the following:

  • PostgreSQL
  • MySQL
  • sqlite 3 and sqlite 2
  • Microsoft SQL Server
  • Oracle
Yii also supports dblib

Some other useful database features supported by Yii include:
  • transactions
  • schema caching for ActiveRecord
  • query caching
  • null conversion
  • database cache dependencies
  • performance profiling

Wednesday, August 10, 2011

Use session instead of stateful forms

Here's why:


  1. If you decide to use AJAX later on (in particular I mean to HIJAX your forms), you'll have to set and get the YII_PAGE_STATE variable for every action, which is a pain in the ass. 
  2. page state is broken when you try to use partial rendering. Even if the partially rendered form is a complete CActiveForm, YII_PAGE_STATE will end up blank. 
I am referring to pages that post back to themselves and that have related sub-items for which you need to maintain state. 

Saturday, August 6, 2011

How to install phpunit on Windows

the PHPUnit installer appears to be written by someone with mild autism....there's no other explanation for it.

either way, here's how i was able to install phpunit:


open the command prompt, type: (enter for each line)
  1. pear channel-update pear.php.net
  2. pear upgrade-all
  3. pear channel-discover pear.phpunit.de
  4. pear channel-discover components.ez.no
  5. pear channel-discover pear.symfony-project.com
  6. pear update-channels
  7. pear install -a -f phpunit/PHPUnit

Monday, July 18, 2011

How to output related values in json

CJSON::encode() is nice for outputting arrays of models or a dataProvider, but it doesnt output relations.

here's how to do it. This function will output an array of models, with their related values (as deep as you wanna go), in JSON format. Instead of showing every attribute, you indicate the ones you want to output using $attributeNames. The key is the CHtml::value() function, that can output related values easily.
/**
   * takes an array of models and their attributes names and outputs them as json. works with relations unlike CJSON::encode()
   * @param $models array an array of models, consider using $dataProvider->getData() here
   * @param $attributeNames string a comma delimited list of attribute names to output, for relations use relationName.attributeName
      * @return void doesn't return anything, but changes content type to json and outputs json and exits
   */

  function json_encode_with_relations(array $models, $attributeNames) {
    $attributeNames = explode(',', $attributeNames);

    $rows = array(); //the rows to output
    foreach ($models as $model) {
      $row = array(); //you will be copying in model attribute values to this array 
      foreach ($attributeNames as $name) {
        $name = trim($name); //in case of spaces around commas
        $row[$name] = CHtml::value($model, $name); //this function walks the relations 
      }
      $rows[] = $row;
    }
    header('Content-type:application/json');
    echo CJSON::encode($rows);
    exit(); //or Yii::app()->end() if you want the log to show in debug mode
  }

//usage:

$myModels = $myDataProvider->getData(); //or you can use $model->findAll();

$modelAttributeNames = 'id, subject, body, someStatisticalRelationName, someRelationName.attribute, someRelationName.someOtherRelationName.attribute';

json_encode_with_relations( $myModels, $modelAttributeNames );

Friday, July 15, 2011

The minimum necessary site structure to run Yii, Part ii

In a previous post , I discussed how to make a minimal site with Yii. Well, here's an even smaller one, with only two files, maybe five lines of code, and no folders:

index.php:
<?
//load yii framework (you'll likely have to change the path):
require_once( dirname(__FILE__).'/../../yii/framework/yii.php' );
//create the app. note that it does not require a config file, you can just pass in an array:
$app = Yii::createWebApplication( array (
  'basePath' => dirname( __FILE__ ) , // if you don't want Protected folder
  'controllerPath' => '' // if you don't want Controllers folder
))->run();

?>
SiteController.php:
<?
class SiteController extends CController
{
  public function actionIndex()
  {
    echo 'hello world';
  }
}
?>
Now, this doesn't work with Gii or crazy things like assets, but that's probably the smallest Yii installation you can make

Friday, July 8, 2011

Using CPropertyValue to convert types

Yii's CPropertyValue class is interesting. It has some useful methods to convert values. Some examples:
var_dump( CPropertyValue::ensureArray( '1,2,a' ) );
/* output: array 0 => string '1,2,3' (length=5) */

var_dump( CPropertyValue::ensureArray( '(1,2,"a")' ) );
/* output:
  array
    0 => int 1
    1=> int 2
    2 => string 'a' (length=1)
 */

var_dump( CPropertyValue::ensureBoolean( "TRUE" ) );
/* output: boolean true */

var_dump( CPropertyValue::ensureBoolean( "yii" ) );
/* output: boolean false */

var_dump( CPropertyValue::ensureFloat( "3.9" ) );
/* output: float 3.9  */

var_dump( CPropertyValue::ensureInteger( "3.9" ) );
/* output: int 3 */

var_dump( CPropertyValue::ensureObject( array("a"=>1, "b"=>2) ) );
/* output:
object(stdClass)[53]
  public 'a' => int 0
  public 'b' => int 1
 */

var_dump( CPropertyValue::ensureString( 5 ) );
/* output: string 5 (length=1) */
ensureEnum ensures that a value is among a list of enumerated values. pass it in a value and a class name that extends CEnumerable and it will throw an error if value is not among the enumerated values.
class SortDirection extends CEnumerable
{
  const Asc="Asc";
  const Desc="Desc";
}

var_dump( CPropertyValue::ensureEnum( "Up" , 'SortDirection' ) );
/* output: throws an error */

var_dump( CPropertyValue::ensureEnum( "Asc" , 'SortDirection' ) );
/* output: string 'Asc' (length=3) */

How to use the Filter Validator in Yii

Here's a quick example on how to use the Filter Validator in Yii.

The filter validator isn't actually a validator, it's a filter :) You give it a php function name to run, and it will run that function on the value of the attribute, when validate() is called.
class Address extends CFormModel /* or CActiveRecord */
{
  public $postal_code;
  public $street;

  public function rules()
  {
    return array(
 //call trim() when validate() is called
 array('street', 'filter', 'filter'=>'trim'),

 /* call my custom function filterPostalCode when validate() is called
  * you can pass it any callback function, but it should only have one parameter
  */
 array('postal_code', 'filter', 'filter'=>array( $this, 'filterPostalCode' )),

 /* if you are going to filter, then you should put the required validator last, as the validators are called in order */
 array('postal_code, street', 'required'),
    );
  }

  public function filterPostalCode($value)
  {
    //strip out non letters and numbers
    $value = preg_replace('/[^A-Za-z0-9]/', '', $value);
    return strtoupper($value);
  }
}
Usage:
$address = new Address;
$address->postal_code ="m5w-1e6";
$address->street = " 123 main street ";
$address->validate();
echo "$address->street $address->postal_code";
$address->postal_code ="/*-*/*-*/-";
$address->street = "     ";
$address->validate();
var_dump($address->errors);
Output:

123 main street M5W1E6
array
  'postal_code' => 
    array
      0 => string 'Postal Code cannot be blank.' (length=28)
  'street' => 
    array
      0 => string 'Street cannot be blank.' (length=23)

Wednesday, June 29, 2011

CClientScript positioning

CClientScript is useful for including css files and javscript files, while avoiding duplication.

Things to know:

1. Yii injects css files just above the <title> tag. So, if you want to always override some included yii style, put your <styles> or <link rel=stylesheets> AFTER the <title> tag, and it will get loaded after the yii styles.

2. I recommend putting all your <styles> and <link rel=stylsheets> in the <head> and all your <scripts> just before </body>. <scripts> are blocking, so your page will load faster if the <scripts> are at the bottom. use:

Yii::app()->getClientScript()->coreScriptPosition = CClientScript::POS_END;

3. if you want to include some inline javascript in a view, but make it load at the bottom, after say jquery, use the registerScript() method. To format your js nicely, you can use the Heredoc syntax:

/* load some formatted js into a php variable: */
$js = <<<EOF
var = 'some javascript here!';
    function() { return 'you can format it as you like, and include php $variables'; };
EOF;

/* write the script at the bottom of the document  */
Yii::app()->getClientScript()->registerScript("some id", $js, CClientScript::POS_END);

Thursday, June 16, 2011

Shades of Grey (or Gray :)

black(Safe 16 SVG Hex3) #000000
gray1 #030303gray2 #050505
gray3 #080808
gray4 #0A0A0Agray5 #0D0D0D
gray6 #0F0F0F
gray7 #121212gray8 #141414
gray9 #171717
gray10 #1A1A1Agray11 #1C1C1C
gray12 #1F1F1F
gray13 #212121gray14 #242424
gray15 #262626
gray16 #292929gray17 #2B2B2B
gray18 #2E2E2E
gray19 #303030gray20(Safe Hex3) #333333
gray21 #363636
gray22 #383838gray23 #3B3B3B
gray24 #3D3D3D
gray25 #404040gray26 #424242
gray27 #454545
gray28 #474747gray29 #4A4A4A
gray30 #4D4D4D
gray31 #4F4F4Fgray32 #525252
gray33(Hex3) #555555
gray34 #575757gray35 #595959
gray36 #5C5C5C
gray37 #5E5E5Egray38 #616161
gray39 #636363
gray40(Safe Hex3) #666666dimgrey(SVG) #696969
dimgray(SVG) #696969
gray42 #6B6B6Bgray43 #6E6E6E
gray44 #707070
gray45 #737373gray46 #757575
gray47 #787878
gray48 #7A7A7Agray49 #7D7D7D
grey(16 SVG) #808080
gray50 #7F7F7Fgray(16 SVG) #808080
gray51 #828282
gray52 #858585gray53 #878787
gray54 #8A8A8A
gray55 #8C8C8Cgray56 #8F8F8F
gray57 #919191
gray58 #949494gray59 #969696
gray60(Safe Hex3) #999999
gray61 #9C9C9Cgray62 #9E9E9E
gray63 #A1A1A1
gray64 #A3A3A3gray65 #A6A6A6
darkgray(SVG) #A9A9A9
gray66 #A8A8A8darkgrey(SVG) #A9A9A9
gray67 #ABABAB
sgilightgray(Hex3) #AAAAAAgray68 #ADADAD
gray69 #B0B0B0
gray70 #B3B3B3gray71 #B5B5B5
gray72 #B8B8B8
gray73 #BABABAgray74 #BDBDBD
silver(16 SVG) #C0C0C0
gray #BEBEBEgray75 #BFBFBF
gray76 #C2C2C2
gray77 #C4C4C4gray78 #C7C7C7
gray79 #C9C9C9
verylightgrey #CDCDCDgray80(Safe Hex3) #CCCCCC
gray81 #CFCFCF
gray82 #D1D1D1gray83 #D4D4D4
lightgrey(SVG) #D3D3D3
lightgray(SVG) #D3D3D3gray84 #D6D6D6
gray85 #D9D9D9
gainsboro(SVG) #DCDCDCgray86 #DBDBDB
gray87 #DEDEDE
gray88 #E0E0E0gray89 #E3E3E3
gray90 #E5E5E5
gray91 #E8E8E8gray92 #EBEBEB
gray93 #EDEDED
gray94 #F0F0F0gray95 #F2F2F2
whitesmoke(SVG) #F5F5F5
gray97 #F7F7F7gray98 #FAFAFA
gray99 #FCFCFC
white(Safe 16 SVG Hex3) #FFFFFF

Cross-Browser CSS Horizontal Centering


/* use for inline (such as text or images) children */
.hcenter-child
{
text-align:center;
}
/*reset the text align, as it inherits*/
.hcenter-child *
{
text-align:left;
}

/* use for block children (ex divs) */
.hcenter
{
width:96%; /*needs any width other than auto*/
margin-left:auto;
margin-right:auto;
}

Cross-Browser CSS Border Radius


.round-borders
{
-moz-border-radius:5px;
-webkit-border-radius:5px;
border-radius:5px;

/*see http://tumble.sneak.co.nz/post/928998513/fixing-the-background-bleed*/
-moz-background-clip: padding;
-webkit-background-clip: padding-box;
background-clip: padding-box;
/*use a behavior file for border radius for IE6-8. see http://www.impressivewebs.com/css3-rounded-corners-in-internet-explorer/ 
or try the jquery corner plugin */

}


Cross-Browser CSS Opacity

.opacity
{
opacity:.5; /*50%*/
filter:alpha(opacity=50);
zoom:1; /*iefix*/
}