1

I am trying to work with namespaces in Fat Free. Everything works fine, but when i ad the namespace, i get this:

Internal Server Error

Fatal error: Class 'Gadgets\iPad' not found

here is my code:

index.php

$f3=require('lib/base.php');

$f3->set('AUTOLOAD','ui/');

$f3->route('GET /', function(){

$obj=new Gadgets\iPad;

echo $obj->hallo('cat');

});

$f3->run();

ui/iPad.php

namespace Gadgets;

class iPad { 

    function hallo($word){ echo $word;}}

Thank you

Liz
  • 189
  • 3
  • 10
  • Not a FFF user, but try `$obj=new \Gadgets\iPad();` so you start from the root namespace. – halfer Dec 15 '13 at 21:04
  • Another thought - if `iPad` is in the `Gadgets` namespace, should it not appear in a "Gadgets" folder? That might be a requirement of the autoloader (again, just a guess). – halfer Dec 15 '13 at 21:06
  • @halfer is right, your class should be in ui/Gadgets/iPad.php – xfra35 Dec 15 '13 at 21:13
  • i thought i have to use a namespace so i do not have to make a Gadgets folder. – Liz Dec 15 '13 at 21:32
  • 2
    Namespaces are here to help you organize your code. If you use them, you can decide to do it with F3 autoloader or not. If you use the autoloader, you have to create a folder for each namespace. If you don't use the autoloader, you can store your files however you like, keeping in mind that you will need to `include` each of them manually. – xfra35 Dec 20 '13 at 09:15
  • @xfra35 this is a very important comment. I suggest we add it to the userguide and reference on the f3 site. I struggled with this for a time as well... – ethanpil Aug 01 '14 at 16:40
  • @ethanpil OK done [here](http://fatfreeframework.com/routing-engine#working-with-namespaces). – xfra35 Sep 15 '14 at 09:08
  • @xfra35 can you please construct your comment into an answer? This actually enlightened me but I was first looking for Questions with answers. – Angel S. Moreno Dec 27 '14 at 03:08
  • 1
    Hi @AngelS.Moreno, glad it helped. I've just published it as an answer. – xfra35 Jan 01 '15 at 21:43

1 Answers1

2

Your class file should appear in the ui\Gadgets folder (full path: ui\Gadgets\iPad.php) in order for F3 to find and autoload it. See this answer for more details on F3's autoloader behaviour.

To answer your comment "i thought i have to use a namespace so i do not have to make a Gadgets folder", here are two points to keep in mind:

  • namespaces are here to help you organize your code: store all the classes related to a common functionality into one same namespace.
  • autoloader is here to help you organize your files: store one class per file and stop caring about require or include calls.

Both functionalities (namespaces/autoloader) are optional. Use them if you understand and need them.

Community
  • 1
  • 1
xfra35
  • 3,833
  • 20
  • 23