Merhaba arkdaşlar, bugün yine yazmak istediğim bir konu var “Extension Methods in c#” ilk once extension amacını anlatmak istiyorum. bildiğiniz üzere .NET framework 3.0 ile LINQ mimarisi üzerine çalışıldı. 2.0 üzerinde oynanma yapılmadan genişletme çabaları da Extensionları doğrumuş. sınıfların LINQ yapısıyla çalışabilmesi için bazı metodlara sahip olması gerekir. bu metodlar extenion yapısıyla bazı classlara eklenmiş oldu.

bize sağladığı güzelliklerin başında “sealed class” (final class) lar için genişletebilme olanağıdır. Object Oriented yapısında genişletme “Inheritance” yani kalıtım ile olur . ancak extensionları kalıtım gibi görmemk lazım. “Delphideki Helper Class”‘ları bilen arkadaşlarımız da bu yapıya yabancı sayılmazlar.

Örnek Olarak:

 

bu metod string sınıfı için yazılmış Int32 dönüşümü yapan bir extension metoddur.

Code completer’ın bize metodları gösterebilmesi de gerçekten  cok iyi.  metodların solundaki Mavi oktan bunların Extension Method olduğunu anlayabiliyoruz.

Küçük bir örnek daha en cok kullandığımız işlemlerden biri olan formlardan sayı gelip gelmediğidir bunu suncuu taraflı kontrol etmek istediğimizde  string  için güzel bi metod olur (:

SQL sorguları gibi kullandığımız LINQ yapısı aslında arka planda metodlarla anlaşır ki bunu gerektiriyor zaten. bir programlama diline adabte edilebilmesi için en mantıklı yöntem seçilmiş.

kısaca extensionları anlatmaya çalıştım arkadaşlar gerisi de sizin hayal gücünüze ve  İhtiyacınıza kalmış.

görüşmek üzere…

Merhaba Arkadaşlar Linq in PHP sınıfımın kullanılabilir son haliyle örnekler vermek istiyorum . Onun öncesinde phpclasses.org da 2010 en iyilerine aday gosterildiğimi söylemek istiyorum. Phpclasses.org yönetici ve tanıdığım en iyi php uzmanı Manuel Lemos Linq in PHP sınıfını 2010 Ocak ayının en iyisi olmaya aday gösterdi oylamalar sanırım ay sonuna kadar devam edecek .. ben de bu süre içinde boş durmayı düşünmüyorum (: sınıfa ilk başladığım gün aklıma gelenleri bile henüz yapabilmiş değilim. – ki sonrasında da neler geldi akla bir bilseniz (:.

CLass : D3Linq Class Source 

Tüm Örnekleri Aynı dizi üzerinde göstermek istiyorum önce bir dizi oluşturalım

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php 
include 'D3Linq.php';
    $Classes=Array(
       'class 1'=>array(
                        'author'=>'Tufan YILDIRIM',
                        'class_name'=>'Linq IN PHP',
                        'author_age'=>20),
       'class 2'=>array(
                        'author'=>'Roman',
                        'class_name'=>'Pearson Significance',
                        'author_age'=>'???'),
       'class 3'=>array(
                        'author'=>'jonathan gotti',
                        'class_name'=>'Very Simple XML Element',
                        'author_age'=>33),
       'class 4'=>array(
                        'author'=>'Piotrek M',
                        'class_name'=>'Cache variables',
                        'author_age'=>'???'),
       'class 5'=>array(
                        'author'=>'Michael A. Peters',
                        'class_name'=>'docType',
                        'author_age'=>37),
       'class 6'=>array(
                        'author'=>'de saint leger christophe',
                        'class_name'=>'Oscar CouchDb',
                        'author_age'=>24),
       'class 7'=>array(
                        'author'=>'Basil Briceño',
                        'class_name'=>'Thunderbird Junk Log To Postfix Header Check',
                        'author_age'=>32),
       'class 8'=>array(
                        'author'=>'Robert',
                        'class_name'=>'xColor',
                        'author_age'=>22),
       'class 9'=>array(
                        'author'=>'Amin Saeedi',
                        'class_name'=>'FLV Metadata',
                        'author_age'=>21),
       'class 10'=>array(
                        'author'=>'Alexander Over',
                        'class_name'=>'Detect Opcode Cache',
                        'author_age'=>28),
       'class 11'=>array(
                        'author'=>'riccardo castagna',
                        'class_name'=>'PreLoad Images',
                        'author_age'=>41)
                   );
         // Objeyi oluşturalım oncelikle.
         $linq=new D3Linq;
0
?>

İlk Örnek Select Sorgumuzu yazalım ..

0
1
2
 $linq->Query("SELECT *FROM Classes WHERE author='Tufan YILDIRIM'");
 $myClass=$linq->fetch_assoc();
 print_r($myClass);

bu da sonuç

Array (  
   [author] => Tufan YILDIRIM
   [class_name] => Linq IN PHP
   [author_age] => 20
)

 

0
1
2
 $linq->Query("SELECT *FROM Classes WHERE age<=20");
 $myClass=$linq->fetch_assoc();
 print_r($myClass);

işte yine aynı sonuç

Array (  
   [author] => Tufan YILDIRIM
   [class_name] => Linq IN PHP
   [author_age] => 20

sardım ben iyice  regex ve yorumlama işine. ufacık bir sql yorumlama sınıfı yaptım. henüz herşeyi yapamasa da bir diziden eleman elemek kolay oldu artk :) fazla uzatmadan class içeriini ver örnek adresi veriyorum

Örnek : http://www.tufyta.com/projects/d3linq/

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
<?php
 /**
 * @name        D3Linq | Linq In Php
 * @version     1.0.1 
 * @author      Tufan Barış YILDIRIM
 * @link        htpp://www.tufyta.com
 * @since       20.10.2009
 * v2
 * =====
 * @todo Sql Group Funcs <SUM,AVG,COUNT etc.>
 * v1.0.1
 * ======
 * - Delete Statemend added. Can Delete any object from an array ( global )        
 * v1.0
 * ======
 * - This Class can be used for select from arrays as a sql query
 * - You;
 * - Can use php codes in Where clauses
 * - Can also use alias for key and value
 * - And can select array in array as  arrayname.elementname
 */
    class D3Linq{
 
      public    $OnError;
 
      private   $Index=0,
                $Result=False,
                $ResultKeys=array(),
                $ResultValues=array(),
                $isBasic=False,
                $isComplicated=False,
                $Tokens,
                $ErrorMsg,
                $ErrorCode;
       #Tokens Index
       const    QR_IDNEX    =0,     // Query Index
                ST_INDEX    =1,     // Statement type Index
                AR_INDEX    =7,     // Array name Index
                CL_INDEX    =3,     // Column Index                          
                AL_COUNT    =8,     // Count of matches for a basic query (without WHERE clause)
                WH_COUNT    =13,    // Count Of matches for a complicated query (with WHERE clauses)
                CM_WHINDEX  =12;    // Where clause index when is complicated
 
       # Errors with Codes        
       const    INVALID_SQL         ='010|Invalid SQL',
                MISSING_OPERATORS   ='020|Missing Operators',
                MISSING_P           ='021|Missing %1 parenthesis',
                UNEXCEPTED_ERROR    ='030|Unexcepted "<b><i>%1</i></b>"',
                EXCEPTED_BUT        ='031|Excepted "<b><i>%1</i></b>"  but found "<i>%2</i>"',
                NOT_AN_ARRAY        ='040|%1 is not an array',             
                NOT_AN_INTEGER      ='041|%1 is not an integer value on %2';                 
      /**
      * Constructor
      */
       public function D3Linq(){
            $this->Index=0;
            $this->ErrorMsg='';
            $this->ErrorCode='';
            $this->ResultKeys=array();
            $this->ResultValues=array();
            $this->Result=False;
            $this->isBasic=False;
            $this->isComplicated=False;
            $this->Tokens=array();
       }
 
       /**
       * Main Qery Parser
       * @param mixed $SQL it must be valid sql query string
       */
       public function Query($SQL){
           $this->D3Linq();    
 
           preg_match('/(SELECT|DELETE)([\s]+)([a-zA-Z0-9\s,]+|\*|.*)?([\s]+)?(FROM)([\s]+)([A-Za-z_0-9\.]+)([\s]+)*((WHERE)([\s]+)([^;]+))*/is',$SQL,$this->Tokens);
 
            switch(count($this->Tokens)) {
               case self::WH_COUNT:
               $this->isComplicated=True;
               break;
               case self::AL_COUNT:
               $this->isBasic=True;
               break;
               default:
                $this->Error(self::INVALID_SQL);
               break;
           }
 
              $RpCount=self::CountIn('\)',$this->Tokens[self::QR_IDNEX]);
              $LpCount=self::CountIn('\(',$this->Tokens[self::QR_IDNEX]);
           if($RpCount!=$LpCount) {
               if($RpCount<$LpCount){
                  $this->Error(self::MISSING_P,'right');
               }else{
                   $this->Error(self::MISSING_P,'left');
               }
           }
           switch (strtoupper($this->Tokens[self::ST_INDEX])){
               case 'SELECT':
               $this->Select($this->Tokens);
               break;
               case 'DELETE':
               $this->Delete($this->Tokens);
               break;
               default:
                $this->Error(self::UNEXCEPTED_ERROR,$this->FirstOf(explode(' ',$SQL)));
               break;
           }
 
       }
       /**
       * Set the index of current Row
       *
       * @param mixed $Int
       */
       public function data_seek($Int){
            if(is_numeric($Int)){
                $this->Index=$Int;
            }else {
                $this->Error(self::NOT_AN_INTEGER,array($Int,__FUNCTION__));
            }
       }
       /**
       * Get Unfetched Count
       * @return int
       */
       public  function num_rows(){
           return count($this->ResultKeys)-$this->Index;
       }
       /**
       * Fetch Result As D3Field. Return false if no result.
       * @return D3Object or False
       */
       public function fetch_object(){
           if($Object=$this->fetch_assoc()){
               return  (object)$Object;
           }
           else {
               return false;
           }
       }
       /**
       * Convert the obje name as  arrayname.indname ..to array arrayname[indname]
       *                              
       * @param mixed $dottedObject
       */
       private function dotObjectToArray($dottedObject){
             if(preg_match('/([A-z0-9_\.]+)/',$dottedObject)){
                 $objs=explode('.',$dottedObject);
                 $arrName=$objs[0];
                 global $$arrName;
                 $globalEleman=$$arrName;
 
                 foreach($objs as  $index=>$name){
                    if($index>0){
                          $globalEleman=$globalEleman[$name];
                          $globalName.=$globalname.'['.$name.']';
                      }else {
                          $globalName=$name;
                      }
                 }  
                 if(!is_array($globalEleman)){
                     $this->Error(self::NOT_AN_ARRAY,$dottedObject);
                 }else {
                     return array('array'=>$globalEleman,'global'=>$globalName,'arrName'=>$arrName);
                 }
             }else {
                 $this->Error(self::NOT_AN_ARRAY,$dottedObject);
             }                   
             return $dottedObject;
 
       }
       /**
       * Fetch Result as an Array. return false if not result
       * @return Array or False
       */
       public function fetch_assoc(){
                if($this->ResultKeys[$this->Index] AND $this->ResultValues[$this->Index]){
                    if($this->Tokens[self::CL_INDEX]=='*')  {
                            $Assoc=array('key'=>$this->ResultKeys[$this->Index],'value'=>$this->ResultValues[$this->Index]);
                    }else {
 
                        preg_match_all('/(key|value)((([\s]+)as)?([\s]+)([^,]+))?/i',$this->Tokens[self::CL_INDEX],$ColumnsWithAlias);
                        foreach($ColumnsWithAlias[1] as $colndx=>$colname){
                            $Assoc[trim($ColumnsWithAlias[6][$colndx] ? $ColumnsWithAlias[6][$colndx] : $colname)]=$colname=='key'?$this->ResultKeys[$this->Index]:$this->ResultValues[$this->Index];
                        }
 
                    }
                    $this->Index++;
                    return $Assoc;
                }
                else {
                    return False;
                }
       }
       /**
       * Main Selector Function
       *
       * @param mixed $Matches Tokens.
       */
       private function Select($Matches){
           $getObj=$this->dotObjectToArray($Matches[self::AR_INDEX]);
           $Dizimiz=$getObj['array'];
           if(!is_array($Dizimiz)){
             $this->Error(self::NOT_AN_ARRAY,$Matches[self::AR_INDEX]);
           }
           if($this->isComplicated){
                    $sart=$Matches[self::CM_WHINDEX];
                    $sart=preg_replace('/(key|value)(=|==|<|>|<=|>=)/i','$$1$2',$sart);
                    $Find=array('key=','value=','\'.key.\'','\'.value.\'');
                    $Replace=array('key==','value==','$key','$value');
                    $sart=str_replace($Find,$Replace,$sart);
                    $sart=preg_replace('/(key|value)([\s]+)(LIKE)*([\s]+)(\')*([^\'\n]+)(\')*/i','preg_match(\'/(\'.str_replace(\'%\',\'(.*)\',\'$6\').\')/i\',$$1)',$sart);
               }else {
                   $sart=true;
               }
 
           foreach ($Dizimiz as $key=>$value){
               @eval('$SartSaglandi=('.$sart.');');
             if($this->isBasic || $SartSaglandi){
                  $this->ResultValues[]=$value;
                  $this->ResultKeys[]=$key;
               }
           }                                                            
           return $this;
       }
 
       /**
       * Main Deleter Function
       *
       * @param mixed $Matches Tokens.
       */
       private function Delete($Matches){
           $getObj=$this->dotObjectToArray($Matches[self::AR_INDEX]);
           $Dizimiz=$getObj['array'];
           if(!is_array($Dizimiz)){
             $this->Error(self::NOT_AN_ARRAY,$Matches[self::AR_INDEX]);
           }
           if($this->isComplicated){
                    $sart=$Matches[self::CM_WHINDEX];
                    $sart=preg_replace('/(key|value)(=|==|<|>|<=|>=)/i','$$1$2',$sart);
                    $Find=array('key=','value=','\'.key.\'','\'.value.\'');
                    $Replace=array('key==','value==','$key','$value');
                    $sart=str_replace($Find,$Replace,$sart);
                    $sart=preg_replace('/(key|value)([\s]+)(LIKE)*([\s]+)(\')*([^\'\n]+)(\')*/i','preg_match(\'/(\'.str_replace(\'%\',\'(.*)\',\'$6\').\')/i\',$$1)',$sart);
               }else {
                   $sart=true;
               }
 
           foreach ($Dizimiz as $key=>$value){
               @eval('$SartSaglandi=('.$sart.');');
             if($this->isBasic || $SartSaglandi){   
                 $deleteCode='global $'.$getObj['arrName'].'; unset($'.$getObj['global'].'['.$key.']);';
                 eval($deleteCode);
 
               }else {
                  $this->ResultValues[]=$value;
                  $this->ResultKeys[]=$key;
               }
           }                                                            
           return $this;
       }
 
       /**
       * Error Creating Function
       *
       * @param mixed $String Error Template
       * @param mixed $Vals  Replace Values
       */
       private function Error($String,$Vals=False){
            $ErrAndCode =explode('|',$String);
            $Error      =strip_tags($ErrAndCode[1]);
            $ErrCode    =$ErrAndCode[0];
 
            if(is_array($Vals)) {
                  foreach($Vals AS $key=>$value){
                      $Error=str_replace('%'.($key+1),$value,$Error);
                  }
                }elseif($Vals){
                    $Error=str_replace('%1',$Vals,$Error);
                }
                $this->ErrorP($Error,$ErrCode);
 
       }
       /**
       * Print Error with Code.
       *
       * @param mixed $String  Error Message
       * @param mixed $Code    Error Code
       */
       private function ErrorP($String,$Code=000){
           $this->ErrorMsg  =$String;
           $this->ErrorCode =$Code;
          if($this->OnError)  {
            $this->RunEvent($this->OnError);
          }else{
            echo '<div><b>#'.$Code.'</b> '.$String."</div>\n";
          }
       }
       /**
       * Return First of Given Array
       *
       * @param mixed $Array
       * @return mixed  First of Array Element
       */
       private function FirstOf($Array){
           return $Array[0];
       }
       /**
       * Find Char Count in a string
       *
       * @param mixed $Needle 
       * @param mixed $Haystack
       * @return int  Char Count
       */
       private function CountIn($Needle,$Haystack){
                 preg_match_all('/([^\\\]['.$Needle.'])/i',$Haystack,$Found);
                 return count($Found[1]);
       }
       /**
       * Event Runner
       *
       * @param mixed $EventName Func Name
       * @param mixed $Param  Func Param(s)
       * @return mixed Func Result which called
       */
       private function RunEvent($EventName,$Param=False){
          if(function_exists($EventName)){
              if($Param){
 
               if(is_array($Param)){
                 return call_user_func_array($EventName,$Param); 
 
               } else {
                 return call_user_func($EventName,$Param);
               }
 
              }else {
                 return call_user_func($EventName);
                   }
            }
      }         
      /**
      * Get Last D3Linq Error Message
      * @return String               
      */
      public function ErrorMsg(){
          return $this->ErrorMsg;
      }
      /**
      * GEt Last D3Linq Error Code
      * @return String                           
      */
      public function ErrorCode(){
          return $this->ErrorCode;
      }
 
   }    
 
?>  
© 2012 Tufan Suffusion theme by Sayontan Sinha