Jump to content
Larry Ullman's Book Forums

Antonio Conte

Members
  • Content Count

    1084
  • Joined

  • Last visited

  • Days Won

    126

Posts posted by Antonio Conte


  1. This error occurs when you try to call a method on something that is not an object. In this case, the variable that should hold an object is actually a boolean. Make sure you actually create an object.

     

    An example can be the MySQLi functions.If you look at MySQLi::query(), the function returns either false (on error) or an object of the type mysql_result. A bad SQL query will make the query fail and the function to return false. The next call to $result->fetch_all(); would therefor return the error above.

     

    In you case, the error occurs when you try to call setFetchMode. It probably means your PDO query failed. Try something like this to reveal the error:

    $query = "..."; // Your current query
    $sth = $dbh->prepare($query);
    $sth->execute();
    
    // Get error array
    $errors = $sth->errorInfo();
    print_r($errors);
    

  2. Just like an array is traversable a closure is callable. The traversable part is why you can foreach an array, as foreach expects something implementing Traversable. You can actually implement Traversable directly on any object and foreach it directly.

     

    The same principle applies to anonymous functions. It's just another type of structure PHP provides you with. Functions in PHP normally provides you encapsulation and execution of a set of logic. A closure is a reference to a function's definition, and behaves more like objects in PHP. When you have a closure, you can do stuff to it, just like you would an object.

    // A reference to a callable function
    $callable = function($text)
    {
        echo $text;
    };
    
    // Perform an operation with a callable
    $callable("I'm running now, guys!"); // Output happens here
    

    call_user_func() and usort() are some of the functions that expects a callable. usort is probably the easiest to get.

    // Define a normaly compare function
    function compare($a, $
    {
        if ($a == $ {
            return 0;
        }
        return ($a < $ ? -1 : 1;
    }
    
    // Use the function normally
    var_dump(compare(1, 1)); // Returns 0, they are equal
    
    // Define an array to sort
    $values = array(3, 1, 2);
    
    // Sort the array using the "compare" function. This probably used call_user_func() 
    // behind the scene to get a callable.
    usort($values, "compare");
    
    // So, let's do that directly instead
    usort($values, function ($a, $ {
        if ($a == $ {
            return 0;
        }
        return ($a < $ ? -1 : 1;
    });
    

    Hope that helps. 


  3. To add to that, .NET just went open source and is available for UNIX systems. That happend very recently.

     

    My advance is to look at Jobs in your community. Also, keep in mind that programming pilars such as algorithms and data structures is appliable to any language. Learn that. Also, learn HTTP if you want to work with the web.


  4. What are your needs here? If this is a read-only (only GET-operations) API, you don't need strict authentication or might not need it at all. Tokens can be used to make sure only those with a valid key can fetch data, you can throttle their calls and build statistics. You could also consider leaving it out completly. If the API is read only, a simple token emailed to users are enough. You can add this token to a GET param or insert into a header in your calls.

     

    1. Seems like a good idea. That way you can also retract tokens.

    2. Probably. How important is security? The tokens generated should take this into account.

    3. You should require users to pass the token upon every request. As you said, there's no state here.

    4. Sounds reasonable.


  5. It's quite normal to build the REST api alongside your site. It seems api.domain.com or domain.com/api/ are pretty normalt structures. While that is the most common, I myself prefer the sort of structure Rails use. This has the added benefit of allowing you to build everything once only. I don't know how easy this is to do with YII, but that's how I build in Symfony. Looking quickly at YII, the same should be possible there.

     

    Some of the reason why this is so easy are some incredible bundles like the FOSRestBundle and JMSSerilizerBundle. By defining core configuration for you app, you're controllers can be configured by annotations only.

     

    Here's an example of that incredible power:

    /**
     * Class MatchController
     * @package JCN\Bundle\ApiBundle\Controller
     *
     * @Route("/match", name="api-match")
     */
    class MatchController extends FOSRestController
    {
        ...
    
        /**
         * @Route("/next", name="api-match-next")
         * @View(templateVar="match")
         * @Template
         */
        public function nextAction()
        {
            $em = $this->getDoctrine()->getManager();
            $next = array_pop($em->getRepository('JCNApiBundle:Fixture')->nextMatch());
    
            return array("match" => $next);
        }
    
        ...
    }
    

    Try the following Curl calls in the command line:

    curl -i -H "Accept: application/json" http://jcn.juvenorge.com/api/match/next

    curl -i -H "Accept: application/html" http://jcn.juvenorge.com/api/match/next

    xmllint --format | curl -i -H "Accept: application/xml" http://jcn.juvenorge.com/api/match/next

     

    To explain some of the magic here, those annotations gets parsed. When that is done, real objects are created behind the. scene, and does all the magic of handling format parsing, view rendering and routing. I can't really explain how much I love Symfony. :)

     

    Edit: I want to add that this structure is not without it's drawback. If you publish your API and want other people using it, this kind of structure is terrible. Then it's more maintanable to offer api.domain.com/v1/action so BC are not broken every time you change something. This API will be for internal use in my own application.


  6. The biggest issue I had was understanding "the flow" of git. If you have get an error, you are doing something wrong. Some typical error cases:

     

    1. You try a git pull origin master (or similar) and get an error. Your local branch is probably not clean. Do a "git status". If you have any changes, do one of two things.

    - If you don't care about saving your changes, you can do something like "git checkout .". That will remove any changes to tracked files. (git checkout file/to/checkout will remove single files) If you've added files using 'git add file/to/add", you can unstage them by doing "git reset file/to/unstage" or all by git reset .". Once the files are unstaged, do a "git checkout ." again. You should now be able to pull.

     

    2. You can't perform a git push origin master. (or similar)

    - You are probably behing the remote. Commit you changes first, do a git pull origin master, then a git pull push origin master.

     

    One of the things that took me a while to understand that comitting and pushing doesn't need to happen right after another. You can always commit changes, but you might not be able to push them to another users commits. When you pull a branch like in the second example, you might get something called a merge conflict. You'll see those as "both added" when doing a git status. Open the file and look at the git merge conflict code. You'll see code like this:

    <<<<<<< HEAD
    nine
    ten
    =======
    eight
    twelve
    >>>>>>> branch-a
    

    If you want to keep 'nine', remove everything but 'nine'. If you want to keep nine and twelve, remove everything but those lines. Conflicts might look a lot more complicated than this, but the same principle applies.

     

    Git has become a trusted friend during the last eight months, and I'm really loving it. It is hard to understand and even harder to master, though. When you get the basics, it works like a dream. I had lots of git problems in the start, but they are all gone now.

     

    Good luck, Jonathon. Git is really worth learning.


  7. Apply some debugging. If you look at your source code, you'll see that the data you try to echo to var date is not correct. Creating JSON out of $_POST will never get you a date.

     

    You are looking for a date on the form "YYYY-MM-DD". To get that, you'll need something more like this:

    var date = "<?php echo $_POST['date_looking']; ?>";

    Some tips. Check you source HTML code and use the Firefox/Chrome debug console to catch any errors.


  8. We use Git Flow on our projects. We also use post-receive hooks and deploy the same way as Larry does. The big difference is that the master branch only have published released, and is thus always stable. We branch out of develop using feature-branches, and merge with develop, perform staging and then goes live when our customers accept new functionality. The stage-enviroment is therefor based on develop, not master. This means we can very easily rollback to a working version if anything stops working and master is always stable. The actual development is performed on our development server that's not visable for the customers.

     

    Additional benefits of using git bare-repos is that can perform additional actions. We must likely need to purge cache, restart varnish and similar. All these steps can be done inside the post-receive script.


  9. Because IE is shit...

     

    On the more serious side, that sounds more like an header issue. I know IE can be a bit weird about headers, so that is nothing new. I experienced the same kind of problem you got a couple of weeks ago. You can find some info here: http://stackoverflow.com/questions/1218925/php-script-to-download-file-not-working-in-ie

     

    If that doesn't work, keep searching Stack Overflow. I used the google term "pdf download php internet explorer".

     

    Good luck and merry Christmas to you guys. :)

    • Upvote 1

  10. I agree on the notion of following standards. With that said, there are no rules without exceptions. I think one-liner if statements are far more readable when you need to assert on state.

    public function someMethod( SomeClass $something )
    {
        if ( ! $this->assertSpecificState($something) ) return;
    
        // No need to worry about the unwanted state. 
    }

    While the above could be written on several lines, it's very expressive yet keeps the noise ratio down.


  11. Happy Holiday, Americans. We don't celebrate thanksgiving here, but it seems like a nice holiday. 

     

    I've been employeed for around six months in my first job now. It's a small and stable company with a total of five developers. We got way to much to do, and the business is fantastic. There I mainly work with development in PHP, but also have other tasks related to server management. eZ Publish and Magento is historically the platforms we work with, but we are moving more and more in the direction of Symfony. With that we build multi-language company sites, eCommerce website and totally custom stuff such as parking systems and certification process management systems.

     

    My biggest improvement got to be with the command line and on Linux systems. Before I started, I tried my best to stay away from the terminal, but it's now one of my most important work-tools. Last week, I configured two Amazon EC2 servers for clients, and provisioned the development stack using PuPHPet. Stuff I hated before, but now really enjoy doing. Moving forward, I'll try getting a Symfony2 certification before Christmas. I'm considering trying out for an eZ Publish one too.

     

    Great to hear from everybody. I'm so busy at the moment I haven't really had time or energy to hang around the forums, but I enjoy reading here from time to time. :)


  12. You problem is that you are not escaping quotes. The sentence in bold I''m confused about normalization uses an apostrophe of the same type as your string declaration. You can't mix and max apostrophes of the same type in strings. "I'm confuced" and 'I "Love" spinach' will work because, while 'I'm confused' and "I "Love" spinach" will break.

     

    You need to escape you input using mysqli_real_escape_string() or by using prepared statements. (Which is recommended. An hour spent googling is worth it)

     

    Also, you'd have problems using these strings in PHP too. Keep that in mind.

    • Upvote 1

  13. Man. It's right there in the Faq. I know you are a beginner, but being able to look for information is perhaps on of the most important skills of any programmer. There's simple to much to know in the programming world to remember it all, so start getting into a habit of at least looking for the answer. :)

     

    I'll quote the FAQ:

     

    The easiest way is to use the security console, which you can access at http://localhost/security/ This console creates a password for the MySQL user root and adjusts the phpMyAdmin configuration.

    Another approach is to configure it with the "XAMPP Shell" (command prompt). Open the shell and execute this command:

    mysqladmin.exe -u root password secret

     

    If you can't get that link working, make sure you've found the Xampp control panel and have started Apache and Mysql. You'll find info on that in the FAQ too.

     

    Also, that said. Keep you spirits up and don't be afraid to ask on the board. There's a lot of awesome people willing to help you out here.

     

    Good luck, man.

    • Upvote 1

  14. Of course. It all depends on your needs, really. Do these accounts need to have specific details or can they have random data? Do you have the password in plain text? You don't give us to much to work with here. ;)

     

    Non-the-less, creating the users should happen inside a loop. In that loop, you'd build all the data you'll need to insert for each user. This can happen trough building a custom query or using PDO.

    $dsn = 'mysql:dbname=YOUR_DATABASE;host=localhost';
    $user = 'dbuser';
    $password = 'dbpass';
    try {
       $dbh = new PDO($dsn, $user, $password);
    } catch (PDOException $e) {
       echo 'Connection failed: ' . $e->getMessage();
    }
    
    // Define the prepared statement "rules"/schema
    // Variables below binds into question mark 1, 2 and 3
    $stmt = $dbhandle->prepare("INSERT INTO users (firstname, lastname, password) VALUES (?, ?, ?)");
    $stmt->bindParam(1, $firstname);
    $stmt->bindParam(2, $lastname);
    $stmt->bindParam(3, $password);
    
    // Some kind of user structure. File/array/etc
    $users = array(
       0 => array("firstname => "'Jon', "lastname => 'Doe', "password" => 'P4ssw0rd'),
       1 => array("firstname => "'Jon', "lastname => 'Doe', "password" => 'P4ssw0rd'),
       3 => array("firstname => "'Jon', "lastname => 'Doe', "password" => 'P4ssw0rd'),
    );
    
    // Intract with your user structure. You'll have to change this a bit
    foreach ( $users as $user ) 
    {
       // Notice how we bind data to the same variables here as in the schema?
       $firstname = $user['firstname'];
       $lastname = $user['lastname'];
       $password = password_hash($user['password'], PASSWORD_DEFAULT);
       $stmt->execute();
    }
    
    // Don't care how the users look like? Along these lines. (I.e skip the user array/file)
    for ($i=0; $i<=50; $i++; )
    {
       $firstname = 'Firstname';
       $lastname = 'Lastname';
       $password = password_hash('123test, PASSWORD_DEFAULT);
       $stmt->execute();
    }
    
    }

    Hope that gives you an idea. This is not a working script, but something to lead you along the way.

     

    Get back to us if something is unclear.

    • Upvote 1

  15. Xampp is a local development stack (think server - with Apache, PHP and Mysql). You'll find a utility inside xampp where you can start both apache and PHP. Depending on your OS, look for a something like xampp-controll.exe on windows or in the xampp folder in applications if your OS X. When that is done, you should be able to hit your local server using http://localhost. This will give you a general XAMPP page with links to PHPMyAdmin (a MySQL web client) and settings such as for admin password. 

     

    Google is also always your friend: https://www.apachefriends.org/faq_osx.html

     

    As Xampp is a local dev server, I wouldn't really care about the admin password to be honest. Leaving it blank is simpler in most cases.

    • Upvote 1

  16. if you have access to both, a Mac would be preferable in most cases. Being familiar with Unix is a huge plus in that regard.

     

    That said, it all depends on your needs. If you are a beginner trying the learn PHP, it does not matter. It matters more when you have production ready code and needs to do more advanced tasks. Being able to use Git for source control is nice, and almost all servers runs on Unix.

     

    As tools go, check out both Sublime and one of Netbeans or Eclipse. All tools are available for both platforms.

     

    In the end, if you need to ask the question, I'm inclined to say it does matter what platform you go for.

×
×
  • Create New...