Kohana 3 Auto loading Models - kohana

I'm attempting to use a Model but I get a fatal error so I assume it doesn't autoload properly.
ErrorException [ Fatal Error ]: Class
'Properties_Model' not found
The offending controller line:
$properties = new Properties_Model;
The model:
class Properties_Model extends Model
{
public function __construct()
{
parent::__construct();
}
}
I also put the class in three different locations hoping one would work, all there failed.
They are:
application/classes/model
application/model
application/models
What am I missing?

Ah, I got this question emailed directly to me (via my website's contact form)!
Here is what I responded with (for the benefit of other people which may run into this problem).
The correct location of a model named
properties is
application/classes/model/properties.php
and the class definition would be as
follows
class Model_Properties extends Model { }
Think of the underscore above as the
directory separator. That is, if you
replaced the underscore with a / you
would have: 'model/properties', which
will be your file under application/classes.
To load the model from a controller,
you can use PHP's standard new
operator or do what I prefer, which is
$propertiesModel = Model::factory('Properties');
I'm not 100% why I prefer this way...
but it works for me :)

First off, The Kohana 3 fileyestem does not work like Kohana 2's!
In K2 the autoloader looks at the class name searches for the class in different folders, based on the suffix of the class.
In K3, class names are "converted" to file paths by replacing underscores with slashes.
i.e. Class Properties_Model becomes classes/properties/model.php
As you can see, using a Model suffix in this new system won't really help to group your models, so basically you prepend "Model" to the class name instead of suffixing it:
Model_Property is located in classes/model/property.php
For more information see the Kohana 3 userguide

Related

ArchUnit: how to test for imports of specific classes outside of current package?

To externalize UI strings we use the "Messages-class" approach as supported e.g. in Eclipse and other IDEs. This approach requires that in each package where one needs some UI strings there has to be a class "Messages" that offers a static method String getString(key) via which one obtains the actual String to display to the user. The Strings are internally accessed/fetched using Java's Resources mechanism for i18n.
Esp. after some refactoring - we again and again have accidental imports from a class Messages from a different package.
Thus I would like to create an archunit rule checking whether we only access classes called "Messages" from the very same package. I.e. each import of a class x.y.z.Messages is an error if the package x.y.z is not the same package as the current class (i.e. the class that contains the import)
I got as far as this:
#ArchTest
void preventReferencesToMessagesOutsideCurrentPackage(JavaClasses classes) {
ArchRule rule;
rule = ArchRuleDefinition.noClasses()
.should().accessClassesThat().haveNameMatching("Messages")
.???
;
rule.check(classes);
}
but now I got stuck at the ???.
How can one phrase a condition "and the referenced/imported class "Messages" is not in the same package as this class"?
I somehow got lost with all these archunit methods of which none seems to fit here nor lend itself to compose said condition. Probably I just can't see the forest for the many trees.
Any suggestion or guidance anyone?
You need to operate on instances of JavaAccess to validate the dependencies. JavaAccess provides information about the caller and the target such that you can validate the access dynamically depending on the package name of both classes.
DescribedPredicate<JavaAccess<?>> isForeignMessageClassPredicate =
new DescribedPredicate<JavaAccess<?>>("target is a foreign message class") {
#Override
public boolean apply(JavaAccess<?> access) {
JavaClass targetClass = access.getTarget().getOwner();
if ("Message".equals(targetClass.getSimpleName())) {
JavaClass callerClass = access.getOwner().getOwner();
return !targetClass.getPackageName().equals(callerClass.getPackageName());
}
return false;
}
};
ArchRule rule =
noClasses().should().accessTargetWhere(isForeignMessageClassPredicate);

Error while executing groovy script

Code is a follows:
class Book
{
private String title
Book (String theTitle)
{
title=theTitle
}
String getTitle()
{
return title
}
}
Book gina=new Book('Groovy in Action')
assert gina.getTitle()=='Groovy in Action'
assert getTitleBackwards(gina)=='noitcA ni yvoorG'
String getTitleBackwards(Book)
{
title=book.getTitle()
return title.reverse()
}
When I execute is with Ctrl+R, I get the following compilation error.
1 compilation error:
Invalid duplicate class definition of class Book : The source
Book.groovy contains at least two definitions of the class Book. One
of the classes is an explicit generated class using the class
statement, the other is a class generated from the script body based
on the file name. Solutions are to change the file name or to change
the class name. at line: 1, column: 1
Can anybody please explain me what is happening here.
Invalid duplicate class definition of class Book:
The code listing of the OP contains two parts:
The type definition of class Book
A groovy script that acts as a client of the Book type
Groovy treats your *.groovy file as either a script file or as a class definition file. A script file is a file that contains code that is not inside a class definition. When Groovy compiles a script file it implicitly creates a class to hold your code and the implicit class is given the name of the Book.groovy file.
Then, the compiler will try and create an additional class Book for the Book class defined in the groovy script, and the error occurs here because now there a actually two Book class definitions.
Compare: Blog entry with code sample for this error message
A way to define the Book class and the client script in the same file would be to rename the file, e.g. to BookApp.groovy. Caveat: if you do this, the Book type can only be referenced from within the script file, the Book type would not be found by groovy automatically, even if the *.groovy file was found on the class path.
Groovy console buffers items (sources, classes, variables) internally, second click of "run" can be different that first, I agree. Almost all interpreter windows (in any languages) has similar behaviour
has delicate differences when opening from File, pasting into window without file, in consequence can have name Book or ConsoleScript1 etc ("procedural" use of Groovy has hidden "object" background, hidden/default/generated class names from file etc)
This can be help-full by ad-hoc programming (script mode) but not always is the best for true OOP.
PS. code has few errors, too
when I ran into this error, it was because I forgot the word 'import' directly above so rather than :
import io.beapi.api.service.PrincipleService
#RestController
class UserController {
I had this:
io.beapi.api.service.PrincipleService
#RestController
class UserController {
The lack of the word import caused this issue for me. Quick easy fix (once I caught what it was) :)

How to perform a search on several entities with Symfony 2

I need to perform a search on several entities with the same string then order the results.
I've heard/read a little about FOSElasticaBundle, would this bundle be able to do it? It seems (to me) to have almost to much features for this purpose and I'm not sure it could run on a shared server (hostgator).
The other solution I can think of at the moment is doing the search "manually" (by using join and union) but I'm wondering where should I put such a function: in an existing controller, a new one, a new bundle or somewhere else?
I'm worried as well that this manual solution could come to a cost, especially on some non-indexable fields.
You would do custom entity repositories. Check out the docs. Basically this extends the default FindAll, FindOneBy, etc.
You would have a function like so:
class MyEntityRepository extends Doctrine\ORM\EntityRepository {
public function findByCustomRule(){
//this is mapped to your entity (automatically adds the select)
$queryBuilder = $this->createQueryBuilder('someAlias');
$queryBuilder->orderBy('...');
//this is mapped to any entity
$queryBuilder = $this->getEntityManager()->createQueryBuilder();
$queryBuilder->select('...');
//result
$result = $queryBuilder->getQuery()->getResult();
}
}
This class is defined in the doctrine mapping and lives inside the Entity folder.. Check the docs out and you should get a basic idea.

Zend_Db_Table_Abstract $_name not working

I encountered a problem regarding changing default table name
class Application_Model_DbTable_Game extends Zend_Db_Table_Abstract
{
protected $_name = 'games';
Error:
Message: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'gamenomad_dev.game' doesn't exist
Help me... it's supposed to be simple!
*EDIT
The problem here is that Zend Framework is supposed to detect the changed table name from the default 'game' into 'games'.
In ZF you have to hardcode your database table to model. It doesn't scan for database changes. You have two ways:
Create class with table name
class Game extends Zend_Db_Table_Abstract
{
// default table name: game
}
If you want to use ZF's default paths, you should put DBTable model into application/models/dbtable directory and name your class like Application_Model_DbTable_Game - then ZF knows it has to look for game table
Create class with any name
e.g. ExtraGameTable and set its parameters to show table name:
class ExtraGameTable extends Zend_Db_Table_Abstract
{
protected $_name = 'game';
}
As stated in documentation: http://framework.zend.com/manual/en/zend.db.table.html
If you don't specify the table name, it defaults to the name of the
class. If you rely on this default, the class name must match the
spelling of the table name as it appears in the database.
You may try to combine it with some configuration file and load table names from there, but still - ZF won't know anything about underlying database changes.
Show the actual line and stacktrace to your problem, maybe you are generating your query in a way it doesn't read the actual table name.

Add constraints to properties of Groovy class (not Grails domain class!)

How can we add some common constraints (i.e. maxLength, nullable) to a property of a Groovy class? I know we can do it at Grails domain class, but is it possible if that is a Groovy class (I use it as a DTO class for my Grails project)?
Thank you so much!
You can add constraints to command classes. If a command class is in the same .groovy file as a controller (in Groovy you can have more than one public class in each .groovy file), you don't need to do anything special for Grails to recongise it as a command class.
However, if your command class is somewhere else (e.g. under src/groovy), you need to annotate it with #Validateable and add the package name to the grails.validateable.packages parameter in Config.groovy. Here's an example of a command that's not in the same file as a controller
pacakge com.example.command
#Validateable
class Person {
Integer age
String name
static constraints = {
name(blank: false)
age(size 0..100)
}
}
Add the following to Config.groovy
grails.validateable.packages = ['com.example.command']
Command classes have a validate() method added by Grails. After this method is called, any errors will be available in the errors property (as per domain classes).
Using a grails Command Object is probably your best bet. It has constraints and validation, but no database backing. It's normally a value object that controllers use, but you could instantiate one outside of a controller without any problems.
Not sure if this is relevant to your use (I am not familiar with DTOs), but in the current version (2.3.8), you can also add Grails constraints to an abstract class, and they will be inherited by the domains that extend it. Your IDE might not like it though ;)

Resources