How do I use add_to in Class::DBI? - perl

I'm trying to use Class::DBI with a simple one parent -> may chidren relationships:
Data::Company->table('Companies');
Data::Company->columns(All => qw/CompanyId Name Url/);
Data::Company->has_many(offers => 'Data::Offer'=>'CompanyId'); # =>'CompanyId'
and
Data::Offer->table('Offers');
Data::Offer->columns(All => qw/OfferId CompanyId MonthlyPrice/);
Data::Offer->has_a(company => 'Data::Company'=>'CompanyId');
I try to add a new record:
my $company = Data::Company->insert({ Name => 'Test', Url => 'http://url' });
my $offer = $company->add_to_offers({ MonthlyPrice => 100 });
But I get:
Can't locate object method "add_to_offers" via package "Data::Company"
I looked at the classical Music::CD example, but I cannot figure out what I am doing wrong.

I agree with Manni, if your package declarations are in the same file, then you need to have the class with the has_a() relationship defined first. Otherwise, if they are in different source files, then the documentation states:
Class::DBI should usually be able to
do the right things, as long as all
classes inherit Class::DBI before
'use'ing any other classes.
As to the three-argument form, you are doing it properly. The third arg for has_many() is the column in the foreign class which is a foreign key to this class. That is, Offer has a CompanyId which points to Company's CompanyId.

Thank you
Well, the issue was actually not my code, but my set up. I realized that this morning after powering on my computer:
* Apache + mod_perl on the server
* SMB mount
When I made changes to several files, not all changes seems to be loaded by mod_perl. Restarting Apache solves the issue. I've actually seen this kind of issue in the past where the client and SMB server's time are out of sync.
The code above works fine with 1 file for each module.
Thank you

I really haven't got much experience with Class:DBI, but I'll give this a shot anyway:
The documentation states that: "the class with the has_a() must be defined earlier than the class with the has_many()".
I cannot find any reference to the way you are using has_a and has_many with three arguments which is always 'CompanyId' in your case.

Related

neo4jphp: Cannot instantiate abstract class Everyman\Neo4j\Transport

maybe a simple question but for me as starter with Neo4j a hurdle. I installed the neo4jphp with composer in the same directory as my application. Vendor-Subfolder has been created and the everyman/neo4j folder below is available. For a first test I used this code snippet from the examples:
spl_autoload_register(function ($className) {
$libPath = 'vendor\\';
$classFile = $className.'.php';
$classPath = $libPath.$classFile;
if (file_exists($classPath)) {
require($classPath);
}
});
require('vendor/autoload.php');
use everyman\Neo4j\Client,
everyman\Neo4j\Transport;
$client = new Client(new Transport('localhost', 7474));
print_r($client->getServerInfo());
I always stumple upon the error
Fatal error: Cannot instantiate abstract class Everyman\Neo4j\Transport
Googling brought me to a comment from Josh Adell stating
You can't instantiate Everyman\Neo4j\Transport, since it is an abstract class. You must instantiate Everyman\Neo4j\Transport\Curl or Everyman\Neo4j\Transport\Stream depending on your needs
So I thought I just need to alter the use-statements to
use everyman\Neo4j\Client,
everyman\Neo4j\Transport\Curl;
but this doesnt work, debugging shows, that the autoloader only get "Transport.php" instead of "everyman\Neo4j\Transport\Curl.php". For "Client.php" its still working ("vendor\everyman\Neo4j\Client.php") so I am guessing that the use-statement is wrong or the code is not able to handle an additional subfolder-structure.
Using
require('phar://neo4jphp.phar');
works fine but I read that this is deprecated and should be replaced by composer / autoload.
Anyone has a hint what to change or had the same problem?
Thanks for your time,
Balael
Curl is the default transport. You only need to instantiate your own Transport object if you want to use Stream instead of Curl. If you really want to instantiate your own Curl Transport, the easiest change to your existing code is to modify the use statement to be:
use everyman\Neo4j\Client,
everyman\Neo4j\Transport\Curl as Transport;
Also, you don't need to register your own autoload function if you are using the Composer package. vendor/autoload.php does that for you.
Thanks Josh, I was trying but it seems I still stuck somewhere. I am fine with using the default CURL - so I shrinked the code down to
require('vendor/autoload.php');
use everyman\Neo4j\Client;
$client = new Everyman\Neo4j\Client('localhost', 7474);
print_r($client->getServerInfo());`
The folder structure is main (here are the files and the composer.json with the content
{
"require": {
"everyman/Neo4j": "dev-master"
}
}
and in the subfolder "vendor" we have the "autoload.php" and the subfolder everyman with the related content. When I run the file I come out with
Fatal error: Class 'Everyman\Neo4j\Client' not found
which does not happen when I have the autoloadfunction. I guess I made a mistake somewehere - can you give me a hint?
Thanks a lot, B
Hmmm... I was just trying around and it seems the Transport CLASS is not needed in the use-statement and the class instantiation. This seems to work:
require('vendor/autoload.php');
use everyman\Neo4j\Client;
$client = new Client();
print_r($client->getServerInfo());
also valid for having a dedicated server/port:
$client = new Everyman\Neo4j\Client('localhost', 7474);
If you have more input I would be happy to learn more - thanks, all input & thoughts are very appreciated.
Balael

Zend Framework 2 Override an existing Service?

I am using a zf2 module called GoalioRememberMe and now I want to override its service by my customized service. Or if it is not possible, I want to override the Module.php with my config. Is it possible?
In the Application module. I wrote this line in module.config.php:
'GoalioRememberMe\Service\RememberMe' => 'Application\Service\RememberMe'
Thanks in advance!
This is exactly the reason it is recommended to name the service as the type of the object that is returned. The object GoalioRememberMe\Service\RememberMe is named goaliorememberme_rememberme_service in the service manager. You can check that here.
So the solution is simple, instead of this:
'GoalioRememberMe\Service\RememberMe' => 'Application\Service\RememberMe'
Write this
'goaliorememberme_rememberme_service' => 'Application\Service\RememberMe'
As Jurian said, the service name is goaliorememberme_rememberme_service and it has been set in the getServiceConfig() method. So I wrote this code in the Module.php file in the Application Module:
$serviceManager->
setAllowOverride(true)->
setInvokableClass('goaliorememberme_rememberme_service', 'Application\Service\CustomRememberMe')->
setAllowOverride(false);
And it replaced successfully with my customized service!
Thanks very much to Jurian for the big help!
Actually the service manager first runs a method "canonicalizeName()" which "normalizes" the names as follows:
All _ / \ and - are stripped out
The key is made lowercase
Thus both "GoalioRememberMe\Service\RememberMe" and "goaliorememberme_rememberme_service" become "goalioremembermeremembermeservice" (i.e. they're both the same), thus the error message.
The quickest way to override an existing service is to create a *local.php or *global.php file in the /config/autoload folder. (That folder is identified in config/application.config.php.) Any override files in this folder are process after modules are loaded. If you have duplicate service manager keys, the last one wins.

Rails 4 with CanCan: unknown attribute error after including load_and_authorize_resource

I'm working in Rails 4 and have gotten CanCan to work well with instructions from this issue, except for one use case that I think might be relatively common.
I have a Comment model, which has_many :comments, through: :replies for nested comments. All of this is working well, until I add load_and_authorize_resource to my comments controller. The problem seems to stem from a hidden field sending an optional :parent_comment_id attribute to my create action.
I've permitted this attribute via strong parameters:
def comment_params
params.require(:comment).permit(:content, :parent_comment_id, :post_id, :comment_id, :user_id)
end
So that I can create the association if a :parent_comment_id is included:
if comment_params[:parent_comment_id] != nil
Reply.create({:parent_comment_id => comment_params[:parent_comment_id], :comment_id => #comment.id})
end
But once I add load_and_authorize_resource, I get an unknown attribute error for :parent_comment_id. What am I missing?
Solution came to me in my sleep. Here's what I did to solve the problem:
The only reason comment_params wasn't normally having a problem on create, was because I was excluding the extra :parent_comment_id parameter, like this:
#comment = post.comment.create(comment_params.except(:parent_comment_id))
When CanCan used the comment_params method however, it did no such sanitation. Hence, the problem. It would have been messy to add that sanitation to CanCan on a per-controller basis, so I did what I should have done all along and instead of passing the :parent_comment_id inside :comment, I used hidden_field_tag to pass it outside of :comment and accessed it through plain, old params.
I hope this helps someone else who makes a similar mistake!

Prevent form manipulation in Lithium/mongoDB

I'm writing my first community page with Lithium and mongoDB. I really like the schema-less way of mongo, but there is one problem making it impossible working without a schema:
For instance we have a simple form like this:
<?=$this->form->create();?>
<?=$this->form->field('name',array('label' => 'Topic title'));?>
<?=$this->form->field('text',array('label' => 'Content'));?>
<?=$this->form->submit('create');?>
which will be even simpler saved by this:
if($this->request->is('post')) {
$board_post = BoardPosts::create($this->request->data);
$board_post->save();
}
Now it's possible for everyone to add some form inputs by DOM manipulation with Firebug, Developer Tools etc. Of course that it might be some sensless fields in the database, but maybe someone adds a field, that is really used.
The only way to prevent this, is creating a schema in model. But for me this makes the whole idea of a schema-less database useless, doesn't it? And how to make schemas for different situations/actions, when some fields must not occur?
The Model::save() method accepts a 'whitelist' param in its options. See http://li3.me/docs/lithium/data/Model::save()
$whitelist = array(
'title',
'text'
);
$post = BoardPosts::create();
$post->save($this->request->data, compact('whitelist'));
You can also define protected $_schema in your Model and set protected $_meta = array('locked' => true); which will automatically set the whitelist to the fields defined in your schema. However, it is a good idea to define the whitelist in your controller to avoid attacks like you describe.
This problem is called a mass-assignment vulnerability and exists in many frameworks if developers are not careful.

Enterprise Library Logging tracelistener extension issue with resolving ILogFormatter

I have been sitting with a problem for quite a while now and I just can't seem to find what I'm missing.
I have written a custom trace listener component for Enterprise Library 5.0 for the Logging application block which works but the configured ILogFormatter just won't resolve and so I always end up with the basic string text when it gets handled by my component.
I saw in the enterprise library source code that they use the "Container.ResolvedIfNotNull()" method. It doesn't seem to work for me. I need it to write out a custom formatted string for my component to use. You know, not just the message but the timestamp, machinename, threadId, etc.
Does anyone have any ideas on how to fix this?
Thanks in advance.
Like I've mentioned on this site: http://entlib.codeplex.com/discussions/261749
When you create your CreationExpression in the TraceListener data class make sure you have a flat constructor definition. To put it in other words, don't return:
() => new MyTraceListener(new TraceListenerConfig(..., Container.ResolvedIfNotNull<ILogFormatter>(), ...));
just have it in the constructor of the MyTraceListener:
() => new MyTraceListener(..., Container.ResolvedIfNotNull<ILogFormatter>(), ...);