How to use the File class from the core

Published on and tagged with cakephp  tip

You may have noticed that there exists a File class in the core (cake/libs/file.php). But how can you use it? Let me give you a simple example. It creates a file “test.txt” if it doesn’t exist, and appends the string “hello”.

// app/controllers/test_controller.php
class TestController extends AppController {
    public $uses = array();
		
    public function index() {
        $file = new File(TMP.'test.txt', true);
        $file->append('hello');
			
        exit;
    }
}

In a similar way you can use the other classes available in the cake/libs folder in your application.

Update 2010-01-04: Removed unnecessary call of uses().

10 comments baked

  • KesheR

    Very useful, thanks!

  • Mandy

    Yep, pretty useful. Simple but not discovered yet :)

  • cakebaker

    I am glad it is useful for you :)

  • Troy Schmidt

    Very helpful in keeping the code CakePHP. Also, the Folder create and search functionality is a lot more wow than the File. But both are mighty helpful to have.

  • MJ

    Thanks so much for documenting this. Cake’s documentation is a little sparse on core class featurs like this, which are really handy for, eg. writing temporary files.

  • cakebaker

    @MJ: Cool to hear it is useful for you, thanks :)

  • Selino

    I’m having trouble finding the syntax for deleting an existing file with CakePHP. I would usually use an unlink but I don’t see any documentation for assigning the path value to the File class.

    How do I tell CakePHP to delete a file at $myLocation = “/img/thumbs/” . xxx ?

    Any help would be great. The API is not very helpful since there are no examples or even syntax guides.

  • cakebaker

    @Selino: Deleting a file with the File class is relatively straightforward:

    $file = new File($myLocation);
    if ($file->delete()) {
        echo 'file deleted';
    }

    Hope this helps!

  • Selino

    Ah! Thanks. I wasn’t sure if I was supposed to path the path as a property of the delete command. I appreciate the help.

  • cakebaker

    @Selino: You are welcome. To figure out how to use things in CakePHP it is often a good idea to have a look at the tests.

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License