Welcome Guest, Not a member yet? Register   Sign In
  Functional PHP Extension
Posted by: El Forum - 07-06-2008, 08:30 PM - Replies (20)

[eluser]Jamongkad[/eluser]
Functional PHP Extension

I all it's been a while since my last contribution to this community. But I feel that CI has given us so much in terms of developer happiness. It actually made me appreciate PHP again. Anyways here again is my small contribution to the community.

Just a few months ago I started to appreciate the power and expressiveness of Functional Programming, my work in using languages such as Scheme has opened my mind to new paradigms. I wanted to know if languages such as PHP can atleast scratch the surface of the power of FP.

Unfortunately in order to do anything remotely related to FP the language must support higer order functions(functions as first class citizens) which PHP does not. Lexical Scoping(which PHP does not execute as elegantly as other languages). These and a lot more are required, thus we come to the this humble library. Please note this library is more of a supplement and a helper to your code. I know it helped me a whole and I hope it does the same for you.

I'm currently the maintainer and active contributor to this library and I would like to share with the community the possiblity of writing code in a more functional manner and practicing Paul Graham's theory on power

So without further ado I'm pretty amped to demonstrate the power of this library with a few examples.
In order to load this library one must simple place it in their helpers folder. Change the file name to functional_helper.php and simply autoload it.

Anonymous Functions
The main crux of this library and the reason why I use it. One would want to utilize the power of unnamed functions for tasks that do not generally require the use of named functions. Small throw away tasks that one can utilize.

In order to invoke the use of anonymous functions...now I know some of you might be thinking that PHP has create_function. And I'm here to tell you that in the true spirit of FP anonymous functions immediately return their expressions. Create_function in all it's awkwardness defines it's expressions procedurally.

Here I define two lamdba functions.

Code:
$plus5 = lam('$x','$x + 5');
$times2 = lam('$x','$x * 2');

$combine = $plus5($times2(7));
//the result will be 19
Awesome isn't it? The library is well commented and you can find more examples I cooked up.

Scheme like Begin
This function was borrowed from Scheme and it allows the one to invoke functions by sequence. The function was inspired by the work of Dikini.net and his contributions.

Code:
function say() {
   echo "My";
}

function my() {
   echo " name ";
}

function name() {
   echo " is Mathew Wong.";
}

echo begin(
        say(),
        my(),
        name()
      );

//which would yield "My name is Mathew Wong."

Concat is the missing array reduction operation in PHP. It's closely related to implode.
Code:
$arr = array(
         'My name is Mathew Wong',
         'Ian Kjos is the original author of the Functional PHP library',
         'This is his implementation',
         'I love Functional programming!'
        );
echo concat($arr,'<br/>');
//Which will result....
    My name is Mathew Wong
    Ian Kjos is the original author of the Functional PHP library
    This is his.....
    I love Functional....

These trivial examples obviously do not do the library and it's original author justice. But for the sake of brevity I wanted to show you guys a taste of the expressive power that is contained in this library. There are alot more functions and combinators in the library that if I were to list them all one page would not be enough for this post.

Thank you and if there any questions I'll be more than happy to entertain them.


  Use the codeigniter library in hook class or function,HOWTO
Posted by: El Forum - 07-06-2008, 08:15 PM - Replies (2)

[eluser]Unknown[/eluser]
Hi all:
How use the codeigniter library in hook class or function, such as database class.
Hook Point: pre_controller.
Tks.


  db->escape() double quotes a numeric value
Posted by: El Forum - 07-06-2008, 06:22 PM - No Replies

[eluser]a&w[/eluser]
I had / have problems with CI double quoting a numeric value when running through db->escape().

From system/database/DB_driver.php:

Code:
function escape($str)
   {    
      switch (gettype($str))
      {
         case 'string' : $str = "'".$this->escape_str($str)."'";
            break;
         case 'boolean': $str = ($str === FALSE) ? 0 : 1;
            break;
         default:        $str = ($str === NULL) ? 'NULL' : $str;
            break;
      }
   return $str;
}

When I do something like escape("40"), the $str is recognized as a string so I end up with '"40"'.

Looking into the php manual I found:
Quote:Note: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().
and also:
Quote:Warning
Never use gettype() to test for a certain type, since the returned string may be subject to change in a future version. In addition, it is slow too, as it involves string comparison.

Instead, use the is_* functions.

To wit:
Code:
$type1 = gettype("40");//string
$type2 = is_numeric("40") ? 'numeric' : $type1;//numeric

$escapeVal1 = mysqli_real_escape_string($this->db->conn_id, $val);//"40"
$escapeVal2 = "'".$escapeVal1."'";//"'40'"  .... over escaped

//my workaround:
$val = is_numeric("40") ? floatval($val) : $val;//40 .... so far so good
$val = $this->db->escape($val);//40 .... numeric value retained!

As a result, would something like this be better:
Code:
function escape($str)
   {    
      if (is_numeric($str))
      {
         $str = $str;
      }
      elseif (is_null($str)
      {
         $str = 'NULL';
      }
      elseif (is_bool($str)
      {
         $str = ($str === FALSE) ? 0 : 1;
      } else {
         $str = "'".$this->escape_str($str)."'";
      }

      return $str;
   }


  Developing Codeigniter Libraries with proper Codeigniter / OOP fundamentals
Posted by: El Forum - 07-06-2008, 06:04 PM - Replies (3)

[eluser]TheresonAntaltego[/eluser]
Greetings!

I must thank CI, its amazing documentation, and the video tutorials for helping me complete a jump to more OO thinking. Most OOP examples and tutorials fail to connect with me in a sensical way. I saw how CI relates URI segments to PHP objects and their methods, and OOP clicked for me. Now I get it. I realize PHP 4 and CI may not present the whole picture of OOP programming fundamentals, but I've come a long way. And, beyond the basic hello world introduction, I've jumped right into developing a few codeigniter libraries.

So, I am a little confused as to how to get libraries to talk to each other. Say I have three libraries, one each for XML parsing, making CURL requests, and interfacing to some external API. If the proper way to load each library in CI is as follows:

Code:
... controller ..

... constructor() {

parent::constructor();
$this->load->library('the_xml_library');
$this->load->library('the_curl_library');
$this->load->library('the_external_API_library');
}

I can only see two ways for each to reference each other. The first, would be to use get_instance within the library with dependencies (the external API), and reference the required library by name in the CI super object. In this case, if I wanted to drop in a replacement library for either XML or CURL handling, I'd have to tamper with the API library. That doesn't seem right with the concept of agnostic modularity in program design. eh?

The second, would be to either pass in a reference to an instantiated dependency upon instantiation of the dependant library, or have methods within the libraries used to set references to each other. This also seems a little goofy to me.

Theoretically, each of these libraries should be PHP classes which should (or could) function without CI at all, and/or dropped in and replaced at will if they _are_ operating within CI.

I am missing something. And its either an understanding of how to develop a library for CI, or an understanding of simple OOP principles that would make my libraries pluggable. Class? Bueller?

Thank you so much for your expert tutelage.


  Extending Exceptions redux redux redux
Posted by: El Forum - 07-06-2008, 05:29 PM - No Replies

[eluser]TheresonAntaltego[/eluser]
Greetings All!

CI newbie here. ID# 52,409, with the Local 508 CI Newbies.

I extended the show_404() function in the native exceptions class with success. Example:

Code:
class MY_Exceptions extends CI_Exceptions {

    /**
     * Constructor
     *
     */    
    function MY_Exceptions()
    {
        parent::CI_Exceptions();
    }

    // --------------------------------------------------------------------

    /**
     * 404 Page Not Found Handler
     *
     * @access    private
     * @param    string
     * @return    string
     */
    function show_404($page = '')
    {    
        $heading = '404 Page Not Found --&gt; '.$page;
        $message = 'The page you requested was not found.';

        log_message('error', '404 Page Not Found --&gt; '.$page);
        echo $this->show_error($heading, $message, 'error_404');
        exit;
    }
      

}
// END MY_Exceptions Class

The only change is the concatenation of the passed argument to the heading, so it is visible in the user output. Nice. But. If I try to extend the function to accept additional arguments, and display them instead of the default header and message entirely, it fails to recognize that the arguments were passed. Here is an example.:

Code:
class MY_Exceptions extends CI_Exceptions {

    /**
     * Constructor
     *
     */    
    function MY_Exceptions()
    {
        parent::CI_Exceptions();
    }

    // --------------------------------------------------------------------

    /**
     * 404 Page Not Found Handler
     *
     * @access    private
     * @param    string
     * @return    string
     */
    function show_404($page = '', $heading = '', $message = '')
    {    
        $heading = ($heading == '')
                          ?  '404 Page Not Found --&gt; '.$page
                          :   $heading;

        $message = ($message == '')
                          ?   'The page you requested was not found.'
                          :   $message;

        log_message('error', '404 Page Not Found --&gt; '.$page);
        echo $this->show_error($heading, $message, 'error_404');
        exit;
    }
      

}
// END MY_Exceptions Class


So I know the extension is working, just not what I figured would be basic PHP principles. Any Ideas? Forgive me if a prior Exceptions-related topic covered and answered this problem. And/or if my folly is obvious.


  Error with $this->db->list_fields() when using mysql/mysqli
Posted by: El Forum - 07-06-2008, 03:41 PM - No Replies

[eluser]flojon[/eluser]
When I use the db function list_fields on a table with dashes the tablename is not escaped and the query fails.

Code:
$this->db->list_fields('table-with-dashes');

results in the following query:
Code:
SHOW COLUMNS FROM table-with-dashes
which fails.

Expected query:
Code:
SHOW COLUMNS FROM `table-with-dashes`

This happens with CodeIgniter 1.6.3 and using bot mysql and mysqli db drivers.


  how create of update field ??
Posted by: El Forum - 07-06-2008, 11:56 AM - Replies (5)

[eluser]Asinox[/eluser]
Hi, i want to do this:

When the user go to some links for read the article, i want to update the field 'views' in my table 'tbl_views'...

my function for read articles

Code:
function leer_articulo($id){
               $this->db->select('*');
            $this->db->where('article_id',$id);
            $this->db->where('articles.pub =','1');            
            $this->db->from('articles');
            /*$this->db->join('comments','comments.article_id = articles.id');*/
            $this->db->join('categories', 'categories.categories_id = articles.category_id');            
            $query = $this->db->get();
            return $query->row_array();
            
            $this->db->select('*');
            $this->db->where('article_id',$id);
            $this->db->from('lecturas');
            $query2 = $this->db->get();
            return $query2->row_array();
            
            if($query2->num_rows() == 0){
                $data = array('article_id'=>$id,'lecturas'=>1);
                $this->db->insert('lecturas',$data);
            }else{
                $suma = $row['lecturas'];
                $this->db->where('article_id',$id);
                $this->db->update('lecturas',$suma+1);
            }
            
       }


  Generating Unique ID
Posted by: El Forum - 07-06-2008, 11:14 AM - Replies (15)

[eluser]Kemik[/eluser]
Hello,

I'm trying to generate a unique ID for a personal file upload script. I was looking for a 5 character string consisting of alphanumeric characters, both upper and lower.

Is there any way of making it truly unique? E.g. based off the current time or would that be too much hassle? If it isn't possible I was just going to use the below script and do a check in the database to make sure it hasn't already been used.

Code:
function createRandomPassword() {

    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $pass = '' ;

    while ($i <= 5) {

        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;

    }
    return $pass;
}


  Cannot use output buffering in output buffering display handlers
Posted by: El Forum - 07-06-2008, 09:59 AM - Replies (7)

[eluser]Mitja[/eluser]

Quote:Fatal error: ob_start() [ref.outcontrol]: Cannot use output buffering in output buffering display handlers in C:\HTTPSERVER\wwwroot\bewoop\system\libraries\Exceptions.php on line 160

when i am trying to use

Code:
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-2");
ob_start("ob_iconv_handler"); // start output buffering

how to fix that?


  SOLVED: Only show DB result from last month?
Posted by: El Forum - 07-06-2008, 06:34 AM - Replies (4)

[eluser]Joakim_[/eluser]
Hi.

I have some hard times showing only the last month entries from the DB.

Code:
$this->db->where('entry_date', date("m/d/Y",strtotime("last month")));

This code works but only show the entries with the same date as the current one. Somebody know how to make it show all entries from last month with any date? i have tried replacing the "d" and "Y" with "*" and even zeros but none of it work.


Any help are extremely appreciated! Thanks Smile


Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Latest Threads
Limiting Stack Trace Erro...
by byrallier
8 hours ago
Bug with sessions CI 4.5....
by ALTITUDE_DEV
9 hours ago
codeigniter 3.0.1 equiped...
by JustJohnQ
Today, 10:05 AM
Display a custom error if...
by b126
Today, 06:22 AM
Type error in SYSTEMPATH\...
by DXArc
Today, 06:20 AM
v4.5.1 Bug Fix Released
by LP_bnss
Today, 04:52 AM
Retaining search variable...
by Bosborne
Today, 03:20 AM
Getting supportedLocales ...
by InsiteFX
Today, 12:24 AM
Component help
by InsiteFX
Today, 12:21 AM
composer didn't update to...
by Sarog
Yesterday, 03:56 PM

Forum Statistics
» Members: 85,110
» Latest member: kanagasabai
» Forum threads: 77,573
» Forum posts: 375,957

Full Statistics

Search Forums

(Advanced Search)


Theme © iAndrew 2016 - Forum software by © MyBB